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(X, Y) (((X) < (Y)) ? (X) : (Y))
49 #define MAX(a, b) ((a) > (b) ? (a) : (b))
50 #define OVERLAP(a,b,c,d) (((a)==(c) && (b)==(d)) || MIN((a)+(b), (c)+(d)) - MAX((a), (c)) > 0)
51 #define INTERSECT(x,y,w,h,x1,y1,w1,h1) (OVERLAP((x),(w),(x1),(w1)) && OVERLAP((y),(h),(y1),(h1)))
53 #define update_completions(cs, text, lines) { \
54 compl_delete(cs); \
55 cs = filter(text, lines); \
56 }
58 // TODO: dynamic?
59 #define INITIAL_ITEMS 64
61 #define TODO(s) { \
62 fprintf(stderr, "TODO! " s "\n"); \
63 }
65 #define cannot_allocate_memory { \
66 fprintf(stderr, "Could not allocate memory\n"); \
67 exit(EX_UNAVAILABLE); \
68 }
70 #define check_allocation(a) { \
71 if (a == nil) \
72 cannot_allocate_memory; \
73 }
75 enum state {LOOPING, OK, ERR};
77 enum text_type {PROMPT, COMPL, COMPL_HIGH};
79 struct rendering {
80 Display *d;
81 Window w;
82 GC prompt;
83 GC prompt_bg;
84 GC completion;
85 GC completion_bg;
86 GC completion_highlighted;
87 GC completion_highlighted_bg;
88 #ifdef USE_XFT
89 XftDraw *xftdraw;
90 XftColor xft_prompt;
91 XftColor xft_completion;
92 XftColor xft_completion_highlighted;
93 XftFont *font;
94 #else
95 XFontSet *font;
96 #endif
97 int width;
98 int height;
99 bool horizontal_layout;
100 char *ps1;
101 int ps1len;
102 };
104 struct completions {
105 char *completion;
106 bool selected;
107 struct completions *next;
108 };
110 struct completions *compl_new() {
111 struct completions *c = malloc(sizeof(struct completions));
113 if (c == nil)
114 return c;
116 c->completion = nil;
117 c->selected = false;
118 c->next = nil;
119 return c;
122 void compl_delete(struct completions *c) {
123 free(c);
126 struct completions *compl_select_next(struct completions *c, bool n) {
127 if (c == nil)
128 return nil;
129 if (n) {
130 c->selected = true;
131 return c;
134 struct completions *orig = c;
135 while (c != nil) {
136 if (c->selected) {
137 c->selected = false;
138 if (c->next != nil) {
139 // the current one is selected and the next one exists
140 c->next->selected = true;
141 return c->next;
142 } else {
143 // the current one is selected and the next one is nill,
144 // select the first one
145 orig->selected = true;
146 return orig;
149 c = c->next;
151 return nil;
154 struct completions *compl_select_prev(struct completions *c, bool n) {
155 if (c == nil)
156 return nil;
158 struct completions *cc = c;
160 if (n) // select the last one
161 while (cc != nil) {
162 if (cc->next == nil) {
163 cc->selected = true;
164 return cc;
166 cc = cc->next;
168 else // select the previous one
169 while (cc != nil) {
170 if (cc->next != nil && cc->next->selected) {
171 cc->next->selected = false;
172 cc->selected = true;
173 return cc;
175 cc = cc->next;
178 return nil;
181 struct completions *filter(char *text, char **lines) {
182 int i = 0;
183 struct completions *root = compl_new();
184 struct completions *c = root;
186 for (;;) {
187 char *l = lines[i];
188 if (l == nil)
189 break;
191 if (strstr(l, text) != nil) {
192 c->next = compl_new();
193 c = c->next;
194 c->completion = l;
197 ++i;
200 struct completions *r = root->next;
201 compl_delete(root);
202 return r;
205 // push the character c at the end of the string pointed by p
206 int pushc(char **p, int maxlen, char c) {
207 int len = strnlen(*p, maxlen);
209 if (!(len < maxlen -2)) {
210 maxlen += maxlen >> 1;
211 char *newptr = realloc(*p, maxlen);
212 if (newptr == nil) { // bad!
213 return -1;
215 *p = newptr;
218 (*p)[len] = c;
219 (*p)[len+1] = '\0';
220 return maxlen;
223 int utf8strnlen(char *s, int maxlen) {
224 int len = 0;
225 while (*s && maxlen > 0) {
226 len += (*s++ & 0xc0) != 0x80;
227 maxlen--;
229 return len;
232 // remove the last *glyph* from the *utf8* string!
233 // this is different from just setting the last byte to 0 (in some
234 // cases ofc). The actual implementation is quite inefficient because
235 // it remove the last char until the number of glyphs doesn't change
236 void popc(char *p, int maxlen) {
237 int len = strnlen(p, maxlen);
239 if (len == 0)
240 return;
242 int ulen = utf8strnlen(p, maxlen);
243 while (len > 0 && utf8strnlen(p, maxlen) == ulen) {
244 len--;
245 p[len] = 0;
249 // If the string is surrounded by quotes (`"`) remove them and replace
250 // every `\"` in the string with `"`
251 char *normalize_str(const char *str) {
252 int len = strlen(str);
253 if (len == 0)
254 return nil;
256 char *s = calloc(len, sizeof(char));
257 check_allocation(s);
258 int p = 0;
259 while (*str) {
260 char c = *str;
261 if (*str == '\\') {
262 if (*(str + 1)) {
263 s[p] = *(str + 1);
264 p++;
265 str += 2; // skip this and the next char
266 continue;
267 } else {
268 break;
271 if (c == '"') {
272 str++; // skip only this char
273 continue;
275 s[p] = c;
276 p++;
277 str++;
279 return s;
282 // read an arbitrary long line from stdin and return a pointer to it
283 // TODO: resize the allocated memory to exactly fit the string once
284 // read?
285 char *readline(bool *eof) {
286 int maxlen = 8;
287 char *str = calloc(maxlen, sizeof(char));
288 if (str == nil) {
289 fprintf(stderr, "Cannot allocate memory!\n");
290 exit(EX_UNAVAILABLE);
293 int c;
294 while((c = getchar()) != EOF) {
295 if (c == '\n')
296 return str;
297 else
298 maxlen = pushc(&str, maxlen, c);
300 if (maxlen == -1) {
301 fprintf(stderr, "Cannot allocate memory!\n");
302 exit(EX_UNAVAILABLE);
305 *eof = true;
306 return str;
309 int readlines (char ***lns, int items) {
310 bool finished = false;
311 int n = 0;
312 char **lines = *lns;
313 while (true) {
314 lines[n] = readline(&finished);
316 if (strlen(lines[n]) == 0 || lines[n][0] == '\n') {
317 free(lines[n]);
318 --n; // forget about this line
321 if (finished)
322 break;
324 ++n;
326 if (n == items - 1) {
327 items += items >>1;
328 char **l = realloc(lines, sizeof(char*) * items);
329 check_allocation(l);
330 *lns = l;
331 lines = l;
335 n++;
336 lines[n] = nil;
337 return items;
340 int text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height) {
341 int height;
342 int width;
343 #ifdef USE_XFT
344 XGlyphInfo gi;
345 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
346 height = (r->font->ascent - r->font->descent)/2;
347 width = gi.width - gi.x;
348 #else
349 XRectangle rect;
350 XmbTextExtents(*r->font, str, len, nil, &rect);
351 height = rect.height;
352 width = rect.width;
353 #endif
354 if (ret_width != nil) *ret_width = width;
355 if (ret_height != nil) *ret_height = height;
356 return width;
359 void draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt) {
360 #ifdef USE_XFT
361 XftColor xftcolor;
362 if (tt == PROMPT) xftcolor = r->xft_prompt;
363 if (tt == COMPL) xftcolor = r->xft_completion;
364 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
366 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
367 #else
368 GC gc;
369 if (tt == PROMPT) gc = r->prompt;
370 if (tt == COMPL) gc = r->completion;
371 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
372 Xutf8DrawString(r->d, r->w, *r->font, gc, x, y, str, len);
373 #endif
376 char *strdupn(char *str) {
377 int len = strlen(str);
379 if (str == nil || len == 0)
380 return nil;
382 char *dup = strdup(str);
383 if (dup == nil)
384 return nil;
386 for (int i = 0; i < len; ++i)
387 if (dup[i] == ' ')
388 dup[i] = 'n';
390 return dup;
393 // |------------------|----------------------------------------------|
394 // | 20 char text | completion | completion | completion | compl |
395 // |------------------|----------------------------------------------|
396 void draw_horizontally(struct rendering *r, char *text, struct completions *cs) {
397 // TODO: make these dynamic?
398 int prompt_width = 20; // char
399 int padding = 10;
401 int width, height;
402 char *ps1_dup = strdupn(r->ps1);
403 ps1_dup = ps1_dup == nil ? r->ps1 : ps1_dup;
404 int ps1xlen = text_extents(ps1_dup, r->ps1len, r, &width, &height);
405 free(ps1_dup);
406 int start_at = ps1xlen;
408 start_at = text_extents("n", 1, r, nil, nil);
409 start_at = start_at * prompt_width + padding;
411 int texty = (height + r->height) >>1;
413 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, start_at, r->height);
415 int text_len = strlen(text);
416 if (text_len > prompt_width)
417 text = text + (text_len - prompt_width);
418 draw_string(r->ps1, r->ps1len, padding, texty, r, PROMPT);
419 draw_string(text, MIN(text_len, prompt_width), padding + ps1xlen, texty, r, PROMPT);
421 XFillRectangle(r->d, r->w, r->completion_bg, start_at, 0, r->width, r->height);
423 while (cs != nil) {
424 enum text_type tt = cs->selected ? COMPL_HIGH : COMPL;
425 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
427 int len = strlen(cs->completion);
428 int text_width = text_extents(cs->completion, len, r, nil, nil);
430 XFillRectangle(r->d, r->w, h, start_at, 0, text_width + padding*2, r->height);
432 draw_string(cs->completion, len, start_at + padding, texty, r, tt);
434 start_at += text_width + padding * 2;
436 if (start_at > r->width)
437 break; // don't draw completion if the space isn't enough
439 cs = cs->next;
442 XFlush(r->d);
445 // |-----------------------------------------------------------------|
446 // | prompt |
447 // |-----------------------------------------------------------------|
448 // | completion |
449 // |-----------------------------------------------------------------|
450 // | completion |
451 // |-----------------------------------------------------------------|
452 // TODO: dunno why but in the call to Xutf8DrawString, by logic,
453 // should be padding and not padding*2, but the text doesn't seem to
454 // be vertically centered otherwise....
455 void draw_vertically(struct rendering *r, char *text, struct completions *cs) {
456 int padding = 10; // TODO make this dynamic
458 int height, width;
459 text_extents("fjpgl", 5, r, &width, &height);
460 int start_at = height + padding*2;
462 XFillRectangle(r->d, r->w, r->completion_bg, 0, 0, r->width, r->height);
463 XFillRectangle(r->d, r->w, r->prompt_bg, 0, 0, r->width, start_at);
465 char *ps1_dup = strdupn(r->ps1);
466 ps1_dup = ps1_dup == nil ? r->ps1 : ps1_dup;
467 int ps1xlen = text_extents(ps1_dup, r->ps1len, r, nil, nil);
468 free(ps1_dup);
470 draw_string(r->ps1, r->ps1len, padding, padding*2, r, PROMPT);
471 draw_string(text, strlen(text), padding + ps1xlen, padding*2, r, PROMPT);
473 while (cs != nil) {
474 enum text_type tt = cs->selected ? COMPL_HIGH : COMPL;
475 GC h = cs->selected ? r->completion_highlighted_bg : r->completion_bg;
477 int len = strlen(cs->completion);
478 text_extents(cs->completion, len, r, &width, &height);
479 XFillRectangle(r->d, r->w, h, 0, start_at, r->width, height + padding*2);
480 draw_string(cs->completion, len, padding, start_at + padding*2, r, tt);
482 start_at += height + padding *2;
484 if (start_at > r->height)
485 break; // don't draw completion if the space isn't enough
487 cs = cs->next;
490 XFlush(r->d);
493 void draw(struct rendering *r, char *text, struct completions *cs) {
494 if (r->horizontal_layout)
495 draw_horizontally(r, text, cs);
496 else
497 draw_vertically(r, text, cs);
500 /* Set some WM stuff */
501 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
502 Atom type;
503 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
504 XChangeProperty(
505 d,
506 w,
507 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
508 XInternAtom(d, "ATOM", false),
509 32,
510 PropModeReplace,
511 (unsigned char *)&type,
513 );
515 /* some window managers honor this properties */
516 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
517 XChangeProperty(d,
518 w,
519 XInternAtom(d, "_NET_WM_STATE", false),
520 XInternAtom(d, "ATOM", false),
521 32,
522 PropModeReplace,
523 (unsigned char *)&type,
525 );
527 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
528 XChangeProperty(d,
529 w,
530 XInternAtom(d, "_NET_WM_STATE", false),
531 XInternAtom(d, "ATOM", false),
532 32,
533 PropModeAppend,
534 (unsigned char *)&type,
536 );
538 // setting window hints
539 XClassHint *class_hint = XAllocClassHint();
540 if (class_hint == nil) {
541 fprintf(stderr, "Could not allocate memory for class hint\n");
542 exit(EX_UNAVAILABLE);
544 class_hint->res_name = resname;
545 class_hint->res_class = resclass;
546 XSetClassHint(d, w, class_hint);
547 XFree(class_hint);
549 XSizeHints *size_hint = XAllocSizeHints();
550 if (size_hint == nil) {
551 fprintf(stderr, "Could not allocate memory for size hint\n");
552 exit(EX_UNAVAILABLE);
554 size_hint->flags = PMinSize | PBaseSize;
555 size_hint->min_width = width;
556 size_hint->base_width = width;
557 size_hint->min_height = height;
558 size_hint->base_height = height;
560 XFlush(d);
563 void get_wh(Display *d, Window *w, int *width, int *height) {
564 XWindowAttributes win_attr;
565 XGetWindowAttributes(d, *w, &win_attr);
566 *height = win_attr.height;
567 *width = win_attr.width;
570 // I know this may seem a little hackish BUT is the only way I managed
571 // to actually grab that goddam keyboard. Only one call to
572 // XGrabKeyboard does not always end up with the keyboard grabbed!
573 int take_keyboard(Display *d, Window w) {
574 int i;
575 for (i = 0; i < 100; i++) {
576 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
577 return 1;
578 usleep(1000);
580 return 0;
583 void release_keyboard(Display *d) {
584 XUngrabKeyboard(d, CurrentTime);
587 int parse_integer(const char *str, int default_value, int max) {
588 int len = strlen(str);
589 if (len > 0 && str[len-1] == '%') {
590 char *cpy = strdup(str);
591 check_allocation(cpy);
592 cpy[len-1] = '\0';
593 int val = parse_integer(cpy, default_value, max);
594 free(cpy);
595 return val * max / 100;
598 errno = 0;
599 char *ep;
600 long lval = strtol(str, &ep, 10);
601 if (str[0] == '\0' || *ep != '\0') { // NaN
602 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
603 return default_value;
605 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
606 (lval > INT_MAX || lval < INT_MIN)) {
607 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
608 return default_value;
610 return lval;
613 int parse_int_with_middle(const char *str, int default_value, int max, int self) {
614 if (!strcmp(str, "middle")) {
615 return (max - self)/2;
617 return parse_integer(str, default_value, max);
620 int main() {
621 char **lines = calloc(INITIAL_ITEMS, sizeof(char*));
622 int nlines = readlines(&lines, INITIAL_ITEMS);
624 setlocale(LC_ALL, getenv("LANG"));
626 enum state status = LOOPING;
628 // where the monitor start (used only with xinerama)
629 int offset_x = 0;
630 int offset_y = 0;
632 // width and height of the window
633 int width = 400;
634 int height = 20;
636 // position on the screen
637 int x = 0;
638 int y = 0;
640 char *ps1 = strdup("$ ");
641 check_allocation(ps1);
643 char *fontname = strdup("fixed");
644 check_allocation(fontname);
646 int textlen = 10;
647 char *text = malloc(textlen * sizeof(char));
648 check_allocation(text);
650 struct completions *cs = filter(text, lines);
651 bool nothing_selected = true;
653 // start talking to xorg
654 Display *d = XOpenDisplay(nil);
655 if (d == nil) {
656 fprintf(stderr, "Could not open display!\n");
657 return EX_UNAVAILABLE;
660 // get display size
661 // XXX: is getting the default root window dimension correct?
662 XWindowAttributes xwa;
663 XGetWindowAttributes(d, DefaultRootWindow(d), &xwa);
664 int d_width = xwa.width;
665 int d_height = xwa.height;
667 #ifdef USE_XINERAMA
668 // TODO: this bit still needs to be improved
669 if (XineramaIsActive(d)) {
670 int monitors;
671 XineramaScreenInfo *info = XineramaQueryScreens(d, &monitors);
672 if (info)
673 for (int i = 0; i < monitors; ++i) {
674 if (INTERSECT(x, y, 1, 1, info[i].x_org, info[i].y_org, info[i].width, info[i].height)) {
675 offset_x = info[x].x_org;
676 offset_y = info[y].y_org;
677 d_width = info[i].width;
678 d_height = info[i].height;
681 XFree(info);
683 #endif
685 /* fprintf(stderr, "offset_x:\t%d\n" */
686 /* "offset_y:\t%d\n" */
687 /* "d_width:\t%d\n" */
688 /* "d_height:\t%d\n" */
689 /* , offset_x, offset_y, d_width, d_height); */
691 Colormap cmap = DefaultColormap(d, DefaultScreen(d));
692 XColor p_fg, p_bg,
693 compl_fg, compl_bg,
694 compl_highlighted_fg, compl_highlighted_bg;
696 bool horizontal_layout = true;
698 // read resource
699 XrmInitialize();
700 char *xrm = XResourceManagerString(d);
701 XrmDatabase xdb = nil;
702 if (xrm != nil) {
703 xdb = XrmGetStringDatabase(xrm);
704 XrmValue value;
705 char *datatype[20];
707 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
708 fontname = strdup(value.addr);
709 check_allocation(fontname);
711 else
712 fprintf(stderr, "no font defined, using %s\n", fontname);
714 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == true) {
715 char *v = strdup(value.addr);
716 check_allocation(v);
717 horizontal_layout = !strcmp(v, "horizontal");
718 free(v);
720 else
721 fprintf(stderr, "no layout defined, using horizontal\n");
723 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == true) {
724 free(ps1);
725 ps1 = normalize_str(value.addr);
726 } else
727 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", ps1);
729 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
730 width = parse_integer(value.addr, width, d_width);
731 else
732 fprintf(stderr, "no width defined, using %d\n", width);
734 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
735 height = parse_integer(value.addr, height, d_height);
736 else
737 fprintf(stderr, "no height defined, using %d\n", height);
739 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
740 x = parse_int_with_middle(value.addr, x, d_width, width);
741 else
742 fprintf(stderr, "no x defined, using %d\n", width);
744 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
745 y = parse_int_with_middle(value.addr, y, d_height, height);
746 else
747 fprintf(stderr, "no y defined, using %d\n", height);
749 XColor tmp;
750 // TODO: tmp needs to be free'd after every allocation?
752 // prompt
753 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
754 XAllocNamedColor(d, cmap, value.addr, &p_fg, &tmp);
755 else
756 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
758 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
759 XAllocNamedColor(d, cmap, value.addr, &p_bg, &tmp);
760 else
761 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
763 // completion
764 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
765 XAllocNamedColor(d, cmap, value.addr, &compl_fg, &tmp);
766 else
767 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
769 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
770 XAllocNamedColor(d, cmap, value.addr, &compl_bg, &tmp);
771 else
772 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
774 // completion highlighted
775 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
776 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_fg, &tmp);
777 else
778 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
780 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
781 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_bg, &tmp);
782 else
783 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
784 } else {
785 XColor tmp;
786 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
787 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
788 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
789 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
790 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
791 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
794 // load the font
795 /* XFontStruct *font = XLoadQueryFont(d, fontname); */
796 /* if (font == nil) { */
797 /* fprintf(stderr, "Unable to load %s font\n", fontname); */
798 /* font = XLoadQueryFont(d, "fixed"); */
799 /* } */
800 // load the font
801 #ifdef USE_XFT
802 XftFont *font = XftFontOpenName(d, DefaultScreen(d), fontname);
803 #else
804 char **missing_charset_list;
805 int missing_charset_count;
806 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
807 if (font == nil) {
808 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
809 return EX_UNAVAILABLE;
811 #endif
813 // create the window
814 XSetWindowAttributes attr;
815 attr.override_redirect = true;
817 Window w = XCreateWindow(d, // display
818 DefaultRootWindow(d), // parent
819 x + offset_x, y + offset_y, // x y
820 width, height, // w h
821 0, // border width
822 DefaultDepth(d, DefaultScreen(d)), // depth
823 InputOutput, // class
824 DefaultVisual(d, DefaultScreen(d)), // visual
825 CWOverrideRedirect, // value mask
826 &attr);
828 set_win_atoms_hints(d, w, width, height);
830 // we want some events
831 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeymapStateMask);
833 // make the window appear on the screen
834 XMapWindow(d, w);
836 // wait for the MapNotify event (i.e. the event "window rendered")
837 for (;;) {
838 XEvent e;
839 XNextEvent(d, &e);
840 if (e.type == MapNotify)
841 break;
844 // get the *real* width & height after the window was rendered
845 get_wh(d, &w, &width, &height);
847 // grab keyboard
848 take_keyboard(d, w);
850 // Create some graphics contexts
851 XGCValues values;
852 /* values.font = font->fid; */
854 struct rendering r = {
855 .d = d,
856 .w = w,
857 #ifdef USE_XFT
858 .font = font,
859 #else
860 .font = &font,
861 #endif
862 .prompt = XCreateGC(d, w, 0, &values),
863 .prompt_bg = XCreateGC(d, w, 0, &values),
864 .completion = XCreateGC(d, w, 0, &values),
865 .completion_bg = XCreateGC(d, w, 0, &values),
866 .completion_highlighted = XCreateGC(d, w, 0, &values),
867 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
868 .width = width,
869 .height = height,
870 .horizontal_layout = horizontal_layout,
871 .ps1 = ps1,
872 .ps1len = strlen(ps1)
873 };
875 #ifdef USE_XFT
876 r.xftdraw = XftDrawCreate(d, w, DefaultVisual(d, 0), DefaultColormap(d, 0));
878 // prompt
879 XRenderColor xrcolor;
880 xrcolor.red = p_fg.red;
881 xrcolor.green = p_fg.red;
882 xrcolor.blue = p_fg.red;
883 xrcolor.alpha = 65535;
884 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_prompt);
886 // completion
887 xrcolor.red = compl_fg.red;
888 xrcolor.green = compl_fg.green;
889 xrcolor.blue = compl_fg.blue;
890 xrcolor.alpha = 65535;
891 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion);
893 // completion highlighted
894 xrcolor.red = compl_highlighted_fg.red;
895 xrcolor.green = compl_highlighted_fg.green;
896 xrcolor.blue = compl_highlighted_fg.blue;
897 xrcolor.alpha = 65535;
898 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion_highlighted);
899 #endif
901 // load the colors in our GCs
902 XSetForeground(d, r.prompt, p_fg.pixel);
903 XSetForeground(d, r.prompt_bg, p_bg.pixel);
904 XSetForeground(d, r.completion, compl_fg.pixel);
905 XSetForeground(d, r.completion_bg, compl_bg.pixel);
906 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel);
907 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg.pixel);
909 // open the X input method
910 XIM xim = XOpenIM(d, xdb, resname, resclass);
911 check_allocation(xim);
913 XIMStyles *xis = nil;
914 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
915 fprintf(stderr, "Input Styles could not be retrieved\n");
916 return EX_UNAVAILABLE;
919 XIMStyle bestMatchStyle = 0;
920 for (int i = 0; i < xis->count_styles; ++i) {
921 XIMStyle ts = xis->supported_styles[i];
922 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
923 bestMatchStyle = ts;
924 break;
927 XFree(xis);
929 if (!bestMatchStyle) {
930 fprintf(stderr, "No matching input style could be determined\n");
933 XIC xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
934 check_allocation(xic);
936 // draw the window for the first time
937 draw(&r, text, cs);
939 // main loop
940 while (status == LOOPING) {
941 XEvent e;
942 XNextEvent(d, &e);
944 if (XFilterEvent(&e, w))
945 continue;
947 switch (e.type) {
948 case KeymapNotify:
949 XRefreshKeyboardMapping(&e.xmapping);
950 break;
952 case KeyPress: {
953 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
955 if (ev->keycode == XKeysymToKeycode(d, XK_Tab)) {
956 bool shift = (ev->state & ShiftMask);
957 struct completions *n = shift ? compl_select_prev(cs, nothing_selected)
958 : compl_select_next(cs, nothing_selected);
959 if (n != nil) {
960 nothing_selected = false;
961 free(text);
962 text = strdup(n->completion);
963 if (text == nil) {
964 fprintf(stderr, "Memory allocation error!\n");
965 status = ERR;
966 break;
968 textlen = strlen(text);
970 draw(&r, text, cs);
971 break;
974 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace)) {
975 nothing_selected = true;
976 popc(text, textlen);
977 update_completions(cs, text, lines);
978 draw(&r, text, cs);
979 break;
982 if (ev->keycode == XKeysymToKeycode(d, XK_Return)) {
983 status = OK;
984 break;
987 if (ev->keycode == XKeysymToKeycode(d, XK_Escape)) {
988 status = ERR;
989 break;
992 // try to read what the user pressed
993 int symbol = 0;
994 Status s = 0;
995 Xutf8LookupString(xic, ev, (char*)&symbol, 4, 0, &s);
997 if (s == XBufferOverflow) {
998 // should not happen since there are no utf-8 characters
999 // larger than 24bits, but is something to be aware of when
1000 // used to directly write to a string buffer
1001 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
1002 break;
1004 char *str = (char*)&symbol;
1006 if (ev->state & ControlMask) {
1007 // check for some key bindings
1008 if (!strcmp(str, "")) { // C-u
1009 nothing_selected = true;
1010 for (int i = 0; i < textlen; ++i)
1011 text[i] = 0;
1012 update_completions(cs, text, lines);
1014 if (!strcmp(str, "")) { // C-h
1015 nothing_selected = true;
1016 popc(text, textlen);
1017 update_completions(cs, text, lines);
1019 if (!strcmp(str, "")) { // C-w
1020 nothing_selected = true;
1022 // `textlen` is the length of the allocated string, not the
1023 // length of the ACTUAL string
1024 int p = strlen(text) - 1;
1025 if (p >= 0) { // delete the current char
1026 text[p] = 0;
1027 p--;
1029 while (p >= 0 && isalnum(text[p])) {
1030 text[p] = 0;
1031 p--;
1033 // erase also trailing white space
1034 while (p >= 0 && isspace(text[p])) {
1035 text[p] = 0;
1036 p--;
1038 update_completions(cs, text, lines);
1040 if (!strcmp(str, "\r")) { // C-m
1041 status = OK;
1043 draw(&r, text, cs);
1044 break;
1047 int str_len = strlen(str);
1048 for (int i = 0; i < str_len; ++i) {
1049 textlen = pushc(&text, textlen, str[i]);
1050 if (textlen == -1) {
1051 fprintf(stderr, "Memory allocation error\n");
1052 status = ERR;
1053 break;
1055 nothing_selected = true;
1056 update_completions(cs, text, lines);
1060 draw(&r, text, cs);
1061 break;
1063 default:
1064 fprintf(stderr, "Unknown event %d\n", e.type);
1068 release_keyboard(d);
1070 if (status == OK)
1071 printf("%s\n", text);
1073 for (int i = 0; i < nlines; ++i) {
1074 free(lines[i]);
1077 #ifdef USE_XFT
1078 XftColorFree(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &r.xft_prompt);
1079 XftColorFree(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &r.xft_completion);
1080 XftColorFree(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &r.xft_completion_highlighted);
1081 #endif
1083 free(ps1);
1084 free(fontname);
1085 free(text);
1086 free(lines);
1087 compl_delete(cs);
1089 XDestroyWindow(d, w);
1090 XCloseDisplay(d);
1092 return status == OK ? 0 : 1;