Blob


1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h> // strdup, strnlen, ...
4 #include <ctype.h> // isalnum
5 #include <locale.h> // setlocale
6 #include <unistd.h>
7 #include <sysexits.h>
8 #include <stdbool.h>
9 #include <limits.h>
10 #include <errno.h>
12 #include <X11/Xlib.h>
13 #include <X11/Xutil.h> // XLookupString
14 #include <X11/Xresource.h>
15 #include <X11/Xcms.h> // colors
16 #include <X11/keysym.h>
18 #ifdef USE_XINERAMA
19 # include <X11/extensions/Xinerama.h>
20 #endif
22 #ifdef USE_XFT
23 # include <X11/Xft/Xft.h>
24 #endif
26 #ifndef VERSION
27 # define VERSION "unknown"
28 #endif
30 // Comfy
31 #define nil NULL
33 #define resname "MyMenu"
34 #define resclass "mymenu"
36 #define SYM_BUF_SIZE 4
38 #ifdef USE_XFT
39 # define default_fontname "monospace"
40 #else
41 # define default_fontname "fixed"
42 #endif
44 #define ARGS "hvae:p:P:l:f:W:H:x:y:b:B:t:T:c:C:s:S:"
46 #define MIN(a, b) ((a) < (b) ? (a) : (b))
47 #define MAX(a, b) ((a) > (b) ? (a) : (b))
49 // If we don't have it or we don't want an "ignore case" completion
50 // style, fall back to `strstr(3)`
51 #ifndef USE_STRCASESTR
52 # define strcasestr strstr
53 #endif
55 // The initial number of items to read
56 #define INITIAL_ITEMS 64
58 // Abort if a is nil
59 #define check_allocation(a) { \
60 if (a == nil) { \
61 fprintf(stderr, "Could not allocate memory\n"); \
62 abort(); \
63 } \
64 }
66 #define inner_height(r) (r->height - r->border_n - r->border_s)
67 #define inner_width(r) (r->width - r->border_e - r->border_w)
69 // The possible state of the event loop.
70 enum state {LOOPING, OK, ERR};
72 // for the drawing-related function. The text to be rendered could be
73 // the prompt, a completion or a highlighted completion
74 enum text_type {PROMPT, COMPL, COMPL_HIGH};
76 // These are the possible action to be performed after user input.
77 enum action {
78 EXIT,
79 CONFIRM,
80 NEXT_COMPL,
81 PREV_COMPL,
82 DEL_CHAR,
83 DEL_WORD,
84 DEL_LINE,
85 ADD_CHAR,
86 TOGGLE_FIRST_SELECTED
87 };
89 // A big set of values that needs to be carried around (for drawing
90 // functions). A struct to rule them all
91 struct rendering {
92 Display *d; // connection to xorg
93 Window w;
94 int width;
95 int height;
96 int padding;
97 int x_zero; // the "zero" on the x axis (may not be 0 'cause the border)
98 int y_zero; // the same a x_zero, only for the y axis
100 // The four border
101 int border_n;
102 int border_e;
103 int border_s;
104 int border_w;
106 bool horizontal_layout;
108 // the prompt
109 char *ps1;
110 int ps1len;
112 // colors
113 GC prompt;
114 GC prompt_bg;
115 GC completion;
116 GC completion_bg;
117 GC completion_highlighted;
118 GC completion_highlighted_bg;
119 GC border_n_bg;
120 GC border_e_bg;
121 GC border_s_bg;
122 GC border_w_bg;
123 #ifdef USE_XFT
124 XftFont *font;
125 XftDraw *xftdraw;
126 XftColor xft_prompt;
127 XftColor xft_completion;
128 XftColor xft_completion_highlighted;
129 #else
130 XFontSet *font;
131 #endif
132 };
134 // A simple linked list to store the completions.
135 struct completion {
136 char *completion;
137 struct completion *next;
138 };
140 // Wrap the linked list of completions
141 struct completions {
142 struct completion *completions;
143 int selected;
144 int lenght;
145 };
147 // return a newly allocated (and empty) completion list
148 struct completions *compls_new() {
149 struct completions *cs = malloc(sizeof(struct completions));
151 if (cs == nil)
152 return cs;
154 cs->completions = nil;
155 cs->selected = -1;
156 cs->lenght = 0;
157 return cs;
160 // Return a newly allocated (and empty) completion
161 struct completion *compl_new() {
162 struct completion *c = malloc(sizeof(struct completion));
163 if (c == nil)
164 return c;
166 c->completion = nil;
167 c->next = nil;
168 return c;
171 // delete ONLY the given completion (i.e. does not free c->next...)
172 void compl_delete(struct completion *c) {
173 free(c);
176 // delete the current completion and the next (c->next) and so on...
177 void compl_delete_rec(struct completion *c) {
178 while (c != nil) {
179 struct completion *t = c->next;
180 free(c);
181 c = t;
185 // Delete the wrapper and the whole list
186 void compls_delete(struct completions *cs) {
187 if (cs == nil)
188 return;
190 compl_delete_rec(cs->completions);
191 free(cs);
194 // create a completion list from a text and the list of possible
195 // completions (null terminated). Expects a non-null `cs'.
196 void filter(struct completions *cs, char *text, char **lines) {
197 struct completion *c = compl_new();
198 if (c == nil) {
199 return;
202 cs->completions = c;
204 int index = 0;
205 int matching = 0;
207 while (true) {
208 char *l = lines[index];
209 if (l == nil)
210 break;
212 if (strcasestr(l, text) != nil) {
213 matching++;
215 c->next = compl_new();
216 c = c->next;
217 if (c == nil) {
218 compls_delete(cs);
219 return;
221 c->completion = l;
224 index++;
227 struct completion *f = cs->completions->next;
228 compl_delete(cs->completions);
229 cs->completions = f;
230 cs->lenght = matching;
231 cs->selected = -1;
234 // update the given completion, that is: clean the old cs & generate a new one.
235 void update_completions(struct completions *cs, char *text, char **lines, bool first_selected) {
236 compl_delete_rec(cs->completions);
237 filter(cs, text, lines);
238 if (first_selected && cs->lenght > 0)
239 cs->selected = 0;
242 // select the next, or the previous, selection and update some
243 // state. `text' will be updated with the text of the completion and
244 // `textlen' with the new lenght of `text'. If the memory cannot be
245 // allocated, `status' will be set to `ERR'.
246 void complete(struct completions *cs, bool first_selected, bool p, char **text, int *textlen, enum state *status) {
247 if (cs == nil || cs->lenght == 0)
248 return;
250 // if the first is always selected, and the first entry is different
251 // from the text, expand the text and return
252 if (first_selected
253 && cs->selected == 0
254 && strcmp(cs->completions->completion, *text) != 0
255 && !p) {
256 free(*text);
257 *text = strdup(cs->completions->completion);
258 if (text == nil) {
259 *status = ERR;
260 return;
262 *textlen = strlen(*text);
263 return;
266 int index = cs->selected;
268 if (index == -1 && p)
269 index = 0;
270 index = cs->selected = (cs->lenght + (p ? index - 1 : index + 1)) % cs->lenght;
272 struct completion *n = cs->completions;
274 // find the selected item
275 while (index != 0) {
276 index--;
277 n = n->next;
280 free(*text);
281 *text = strdup(n->completion);
282 if (text == nil) {
283 fprintf(stderr, "Memory allocation error!\n");
284 *status = ERR;
285 return;
287 *textlen = strlen(*text);
290 // push the character c at the end of the string pointed by p
291 int pushc(char **p, int maxlen, char c) {
292 int len = strnlen(*p, maxlen);
294 if (!(len < maxlen -2)) {
295 maxlen += maxlen >> 1;
296 char *newptr = realloc(*p, maxlen);
297 if (newptr == nil) { // bad!
298 return -1;
300 *p = newptr;
303 (*p)[len] = c;
304 (*p)[len+1] = '\0';
305 return maxlen;
308 // remove the last rune from the *utf8* string! This is different from
309 // just setting the last byte to 0 (in some cases ofc). Return a
310 // pointer (e) to the last non zero char. If e < p then p is empty!
311 char* popc(char *p) {
312 int len = strlen(p);
313 if (len == 0)
314 return p;
316 char *e = p + len - 1;
318 do {
319 char c = *e;
320 *e = 0;
321 e--;
323 // if c is a starting byte (11......) or is under U+007F (ascii,
324 // basically) we're done
325 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
326 break;
327 } while (e >= p);
329 return e;
332 // remove the last word plus trailing whitespaces from the give string
333 void popw(char *w) {
334 int len = strlen(w);
335 if (len == 0)
336 return;
338 bool in_word = true;
339 while (true) {
340 char *e = popc(w);
342 if (e < w)
343 return;
345 if (in_word && isspace(*e))
346 in_word = false;
348 if (!in_word && !isspace(*e))
349 return;
353 // If the string is surrounded by quotes (`"`) remove them and replace
354 // every `\"` in the string with `"`
355 char *normalize_str(const char *str) {
356 int len = strlen(str);
357 if (len == 0)
358 return nil;
360 char *s = calloc(len, sizeof(char));
361 check_allocation(s);
362 int p = 0;
363 while (*str) {
364 char c = *str;
365 if (*str == '\\') {
366 if (*(str + 1)) {
367 s[p] = *(str + 1);
368 p++;
369 str += 2; // skip this and the next char
370 continue;
371 } else {
372 break;
375 if (c == '"') {
376 str++; // skip only this char
377 continue;
379 s[p] = c;
380 p++;
381 str++;
383 return s;
386 // read an arbitrary long line from stdin and return a pointer to it
387 // TODO: resize the allocated memory to exactly fit the string once
388 // read?
389 char *readline(bool *eof) {
390 int maxlen = 8;
391 char *str = calloc(maxlen, sizeof(char));
392 if (str == nil) {
393 fprintf(stderr, "Cannot allocate memory!\n");
394 exit(EX_UNAVAILABLE);
397 int c;
398 while((c = getchar()) != EOF) {
399 if (c == '\n')
400 return str;
401 else
402 maxlen = pushc(&str, maxlen, c);
404 if (maxlen == -1) {
405 fprintf(stderr, "Cannot allocate memory!\n");
406 exit(EX_UNAVAILABLE);
409 *eof = true;
410 return str;
413 // read an arbitrary amount of text until an EOF and store it in
414 // lns. `items` is the capacity of lns. It may increase lns with
415 // `realloc(3)` to store more line. Return the number of lines
416 // read. The last item will always be a NULL pointer. It ignore the
417 // "null" (empty) lines
418 int readlines (char ***lns, int items) {
419 bool finished = false;
420 int n = 0;
421 char **lines = *lns;
422 while (true) {
423 lines[n] = readline(&finished);
425 if (strlen(lines[n]) == 0 || lines[n][0] == '\n') {
426 free(lines[n]);
427 --n; // forget about this line
430 if (finished)
431 break;
433 ++n;
435 if (n == items - 1) {
436 items += items >>1;
437 char **l = realloc(lines, sizeof(char*) * items);
438 check_allocation(l);
439 *lns = l;
440 lines = l;
444 n++;
445 lines[n] = nil;
446 return items;
449 // Compute the dimension of the string str once rendered, return the
450 // width and save the width and the height in ret_width and ret_height
451 int text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height) {
452 int height;
453 int width;
454 #ifdef USE_XFT
455 XGlyphInfo gi;
456 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
457 /* height = gi.height; */
458 /* height = (gi.height + (r->font->ascent - r->font->descent)/2) / 2; */
459 /* height = (r->font->ascent - r->font->descent)/2 + gi.height*2; */
460 height = r->font->ascent - r->font->descent;
461 width = gi.width - gi.x;
462 #else
463 XRectangle rect;
464 XmbTextExtents(*r->font, str, len, nil, &rect);
465 height = rect.height;
466 width = rect.width;
467 #endif
468 if (ret_width != nil) *ret_width = width;
469 if (ret_height != nil) *ret_height = height;
470 return width;
473 // Draw the string str
474 void draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt) {
475 #ifdef USE_XFT
476 XftColor xftcolor;
477 if (tt == PROMPT) xftcolor = r->xft_prompt;
478 if (tt == COMPL) xftcolor = r->xft_completion;
479 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
481 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
482 #else
483 GC gc;
484 if (tt == PROMPT) gc = r->prompt;
485 if (tt == COMPL) gc = r->completion;
486 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
487 Xutf8DrawString(r->d, r->w, *r->font, gc, x, y, str, len);
488 #endif
491 // Duplicate the string str and substitute every space with a 'n'
492 char *strdupn(char *str) {
493 int len = strlen(str);
495 if (str == nil || len == 0)
496 return nil;
498 char *dup = strdup(str);
499 if (dup == nil)
500 return nil;
502 for (int i = 0; i < len; ++i)
503 if (dup[i] == ' ')
504 dup[i] = 'n';
506 return dup;
509 // |------------------|----------------------------------------------|
510 // | 20 char text | completion | completion | completion | compl |
511 // |------------------|----------------------------------------------|
512 void draw_horizontally(struct rendering *r, char *text, struct completions *cs) {
513 int prompt_width = 20; // char
515 int width, height;
516 int ps1xlen = text_extents(r->ps1, r->ps1len, r, &width, &height);
517 int start_at = ps1xlen;
519 start_at = r->x_zero + text_extents("n", 1, r, nil, nil);
520 start_at = start_at * prompt_width + r->padding;
522 int texty = (inner_height(r) + height + r->y_zero) / 2;
524 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, start_at, inner_height(r));
526 int text_len = strlen(text);
527 if (text_len > prompt_width)
528 text = text + (text_len - prompt_width);
529 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, texty, r, PROMPT);
530 draw_string(text, MIN(text_len, prompt_width), r->x_zero + r->padding + ps1xlen, texty, r, PROMPT);
532 XFillRectangle(r->d, r->w, r->completion_bg, start_at, r->y_zero, r->width, inner_height(r));
534 struct completion *c = cs->completions;
535 for (int i = 0; c != nil; ++i) {
536 enum text_type tt = cs->selected == i ? COMPL_HIGH : COMPL;
537 GC h = cs->selected == i ? r->completion_highlighted_bg : r->completion_bg;
539 int len = strlen(c->completion);
540 int text_width = text_extents(c->completion, len, r, nil, nil);
542 XFillRectangle(r->d, r->w, h, start_at, r->y_zero, text_width + r->padding*2, inner_height(r));
544 draw_string(c->completion, len, start_at + r->padding, texty, r, tt);
546 start_at += text_width + r->padding * 2;
548 if (start_at > inner_width(r))
549 break; // don't draw completion if the space isn't enough
551 c = c->next;
555 // |-----------------------------------------------------------------|
556 // | prompt |
557 // |-----------------------------------------------------------------|
558 // | completion |
559 // |-----------------------------------------------------------------|
560 // | completion |
561 // |-----------------------------------------------------------------|
562 void draw_vertically(struct rendering *r, char *text, struct completions *cs) {
563 int height, width;
564 text_extents("fjpgl", 5, r, nil, &height);
565 int start_at = height + r->padding;
567 XFillRectangle(r->d, r->w, r->completion_bg, r->x_zero, r->y_zero, r->width, r->height);
568 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, r->width, start_at);
570 int ps1xlen = text_extents(r->ps1, r->ps1len, r, nil, nil);
572 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, r->y_zero + height + r->padding, r, PROMPT);
573 draw_string(text, strlen(text), r->x_zero + r->padding + ps1xlen, r->y_zero + height + r->padding, r, PROMPT);
575 start_at += r->padding + r->y_zero;
577 struct completion *c = cs->completions;
578 for (int i = 0; c != nil; ++i){
579 enum text_type tt = cs->selected == i ? COMPL_HIGH : COMPL;
580 GC h = cs->selected == i ? r->completion_highlighted_bg : r->completion_bg;
582 int len = strlen(c->completion);
583 text_extents(c->completion, len, r, &width, &height);
584 XFillRectangle(r->d, r->w, h, r->x_zero, start_at, inner_width(r), height + r->padding*2);
585 draw_string(c->completion, len, r->x_zero + r->padding, start_at + height + r->padding, r, tt);
587 start_at += height + r->padding *2;
589 if (start_at > inner_height(r))
590 break; // don't draw completion if the space isn't enough
592 c = c->next;
596 void draw(struct rendering *r, char *text, struct completions *cs) {
597 if (r->horizontal_layout)
598 draw_horizontally(r, text, cs);
599 else
600 draw_vertically(r, text, cs);
602 // draw the borders
604 if (r->border_w != 0)
605 XFillRectangle(r->d, r->w, r->border_w_bg, 0, 0, r->border_w, r->height);
607 if (r->border_e != 0)
608 XFillRectangle(r->d, r->w, r->border_e_bg, r->width - r->border_e, 0, r->border_e, r->height);
610 if (r->border_n != 0)
611 XFillRectangle(r->d, r->w, r->border_n_bg, 0, 0, r->width, r->border_n);
613 if (r->border_s != 0)
614 XFillRectangle(r->d, r->w, r->border_s_bg, 0, r->height - r->border_s, r->width, r->border_s);
616 // send all the work to x
617 XFlush(r->d);
620 /* Set some WM stuff */
621 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
622 Atom type;
623 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
624 XChangeProperty(
625 d,
626 w,
627 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
628 XInternAtom(d, "ATOM", false),
629 32,
630 PropModeReplace,
631 (unsigned char *)&type,
633 );
635 /* some window managers honor this properties */
636 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
637 XChangeProperty(d,
638 w,
639 XInternAtom(d, "_NET_WM_STATE", false),
640 XInternAtom(d, "ATOM", false),
641 32,
642 PropModeReplace,
643 (unsigned char *)&type,
645 );
647 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
648 XChangeProperty(d,
649 w,
650 XInternAtom(d, "_NET_WM_STATE", false),
651 XInternAtom(d, "ATOM", false),
652 32,
653 PropModeAppend,
654 (unsigned char *)&type,
656 );
658 // setting window hints
659 XClassHint *class_hint = XAllocClassHint();
660 if (class_hint == nil) {
661 fprintf(stderr, "Could not allocate memory for class hint\n");
662 exit(EX_UNAVAILABLE);
664 class_hint->res_name = resname;
665 class_hint->res_class = resclass;
666 XSetClassHint(d, w, class_hint);
667 XFree(class_hint);
669 XSizeHints *size_hint = XAllocSizeHints();
670 if (size_hint == nil) {
671 fprintf(stderr, "Could not allocate memory for size hint\n");
672 exit(EX_UNAVAILABLE);
674 size_hint->flags = PMinSize | PBaseSize;
675 size_hint->min_width = width;
676 size_hint->base_width = width;
677 size_hint->min_height = height;
678 size_hint->base_height = height;
680 XFlush(d);
683 // write the width and height of the window `w' respectively in `width'
684 // and `height'.
685 void get_wh(Display *d, Window *w, int *width, int *height) {
686 XWindowAttributes win_attr;
687 XGetWindowAttributes(d, *w, &win_attr);
688 *height = win_attr.height;
689 *width = win_attr.width;
692 int grabfocus(Display *d, Window w) {
693 for (int i = 0; i < 100; ++i) {
694 Window focuswin;
695 int revert_to_win;
696 XGetInputFocus(d, &focuswin, &revert_to_win);
697 if (focuswin == w)
698 return true;
699 XSetInputFocus(d, w, RevertToParent, CurrentTime);
700 usleep(1000);
702 return 0;
705 // I know this may seem a little hackish BUT is the only way I managed
706 // to actually grab that goddam keyboard. Only one call to
707 // XGrabKeyboard does not always end up with the keyboard grabbed!
708 int take_keyboard(Display *d, Window w) {
709 int i;
710 for (i = 0; i < 100; i++) {
711 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
712 return 1;
713 usleep(1000);
715 fprintf(stderr, "Cannot grab keyboard\n");
716 return 0;
719 // release the keyboard.
720 void release_keyboard(Display *d) {
721 XUngrabKeyboard(d, CurrentTime);
724 // Given a string, try to parse it as a number or return
725 // `default_value'.
726 int parse_integer(const char *str, int default_value) {
727 errno = 0;
728 char *ep;
729 long lval = strtol(str, &ep, 10);
730 if (str[0] == '\0' || *ep != '\0') { // NaN
731 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
732 return default_value;
734 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
735 (lval > INT_MAX || lval < INT_MIN)) {
736 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
737 return default_value;
739 return lval;
742 // like parse_integer, but if the value ends with a `%' then its
743 // treated like a percentage (`max' is used to compute the percentage)
744 int parse_int_with_percentage(const char *str, int default_value, int max) {
745 int len = strlen(str);
746 if (len > 0 && str[len-1] == '%') {
747 char *cpy = strdup(str);
748 check_allocation(cpy);
749 cpy[len-1] = '\0';
750 int val = parse_integer(cpy, default_value);
751 free(cpy);
752 return val * max / 100;
754 return parse_integer(str, default_value);
757 // like parse_int_with_percentage but understands some special values
758 // - "middle" that is (max - self) / 2
759 // - "start" that is 0
760 // - "end" that is (max - self)
761 int parse_int_with_pos(const char *str, int default_value, int max, int self) {
762 if (!strcmp(str, "start"))
763 return 0;
764 if (!strcmp(str, "middle"))
765 return (max - self)/2;
766 if (!strcmp(str, "end"))
767 return max-self;
768 return parse_int_with_percentage(str, default_value, max);
771 // parse a string like a css value (for example like the css
772 // margin/padding properties). Will ALWAYS return an array of 4 word
773 // TODO: harden this function!
774 char **parse_csslike(const char *str) {
775 char *s = strdup(str);
776 if (s == nil)
777 return nil;
779 char **ret = malloc(4 * sizeof(char*));
780 if (ret == nil) {
781 free(s);
782 return nil;
785 int i = 0;
786 char *token;
787 while ((token = strsep(&s, " ")) != NULL && i < 4) {
788 ret[i] = strdup(token);
789 i++;
792 if (i == 1)
793 for (int j = 1; j < 4; j++)
794 ret[j] = strdup(ret[0]);
796 if (i == 2) {
797 ret[2] = strdup(ret[0]);
798 ret[3] = strdup(ret[1]);
801 if (i == 3)
802 ret[3] = strdup(ret[1]);
804 // Before we didn't check for the return type of strdup, here we will
806 bool any_null = false;
807 for (int i = 0; i < 4; ++i)
808 any_null = ret[i] == nil || any_null;
810 if (any_null)
811 for (int i = 0; i < 4; ++i)
812 if (ret[i] != nil)
813 free(ret[i]);
815 if (i == 0 || any_null) {
816 free(s);
817 free(ret);
818 return nil;
821 return ret;
824 // Given an event, try to understand what the user wants. If the
825 // return value is ADD_CHAR then `input' is a pointer to a string that
826 // will need to be free'ed.
827 enum action parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input) {
828 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
829 return DEL_CHAR;
831 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
832 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
834 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
835 return CONFIRM;
837 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
838 return EXIT;
840 // try to read what the user pressed
841 char str[SYM_BUF_SIZE] = {0};
842 Status s = 0;
843 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
844 if (s == XBufferOverflow) {
845 // should not happen since there are no utf-8 characters larger
846 // than 24bits
847 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
848 return EXIT;
851 if (ev->state & ControlMask) {
852 if (!strcmp(str, "")) // C-u
853 return DEL_LINE;
854 if (!strcmp(str, "")) // C-w
855 return DEL_WORD;
856 if (!strcmp(str, "")) // C-h
857 return DEL_CHAR;
858 if (!strcmp(str, "\r")) // C-m
859 return CONFIRM;
860 if (!strcmp(str, "")) // C-p
861 return PREV_COMPL;
862 if (!strcmp(str, "")) // C-n
863 return NEXT_COMPL;
864 if (!strcmp(str, "")) // C-c
865 return EXIT;
866 if (!strcmp(str, "\t")) // C-i
867 return TOGGLE_FIRST_SELECTED;
870 *input = strdup(str);
871 if (*input == nil) {
872 fprintf(stderr, "Error while allocating memory for key.\n");
873 return EXIT;
876 return ADD_CHAR;
879 // Given the name of the program (argv[0]?) print a small help on stderr
880 void usage(char *prgname) {
881 fprintf(stderr, "%s [-hva] [-p prompt] [-x coord] [-y coord] [-W width] [-H height]\n"
882 " [-P padding] [-l layout] [-f font] [-b borders] [-B colors]\n"
883 " [-t color] [-T color] [-c color] [-C color] [-s color] [-S color]\n"
884 " [-w window_id]\n", prgname);
887 int main(int argc, char **argv) {
888 #ifdef HAVE_PLEDGE
889 // stdio & rpat: to read and write stdio/stdout
890 // unix: to connect to Xorg
891 pledge("stdio rpath unix", "");
892 #endif
894 // by default the first completion isn't selected
895 bool first_selected = false;
897 // our parent window
898 char *parent_window_id = nil;
900 // first round of args parsing
901 int ch;
902 while ((ch = getopt(argc, argv, ARGS)) != -1) {
903 switch (ch) {
904 case 'h': // help
905 usage(*argv);
906 return 0;
907 case 'v': // version
908 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
909 return 0;
910 case 'e': // embed
911 parent_window_id = strdup(optarg);
912 check_allocation(parent_window_id);
913 break;
914 default:
915 break;
919 // read the lines from stdin
920 char **lines = calloc(INITIAL_ITEMS, sizeof(char*));
921 readlines(&lines, INITIAL_ITEMS);
923 setlocale(LC_ALL, getenv("LANG"));
925 enum state status = LOOPING;
927 // where the monitor start (used only with xinerama)
928 int offset_x = 0;
929 int offset_y = 0;
931 // width and height of the window
932 int width = 400;
933 int height = 20;
935 // position on the screen
936 int x = 0;
937 int y = 0;
939 // the default padding
940 int padding = 10;
942 // the default borders
943 int border_n = 0;
944 int border_e = 0;
945 int border_s = 0;
946 int border_w = 0;
948 // the prompt. We duplicate the string so later is easy to free (in
949 // the case the user provide its own prompt)
950 char *ps1 = strdup("$ ");
951 check_allocation(ps1);
953 // same for the font name
954 char *fontname = strdup(default_fontname);
955 check_allocation(fontname);
957 int textlen = 10;
958 char *text = malloc(textlen * sizeof(char));
959 check_allocation(text);
961 /* struct completions *cs = filter(text, lines); */
962 struct completions *cs = compls_new();
963 check_allocation(cs);
965 // start talking to xorg
966 Display *d = XOpenDisplay(nil);
967 if (d == nil) {
968 fprintf(stderr, "Could not open display!\n");
969 return EX_UNAVAILABLE;
972 Window parent_window;
973 bool embed = true;
974 if (! (parent_window_id && (parent_window = strtol(parent_window_id, nil, 0)))) {
975 parent_window = DefaultRootWindow(d);
976 embed = false;
979 // get display size
980 int d_width;
981 int d_height;
982 get_wh(d, &parent_window, &d_width, &d_height);
984 fprintf(stderr, "d_width %d, d_height %d\n", d_width, d_height);
986 #ifdef USE_XINERAMA
987 if (!embed && XineramaIsActive(d)) {
988 // find the mice
989 int number_of_screens = XScreenCount(d);
990 Window r;
991 Window root;
992 int root_x, root_y, win_x, win_y;
993 unsigned int mask;
994 bool res;
995 for (int i = 0; i < number_of_screens; ++i) {
996 root = XRootWindow(d, i);
997 res = XQueryPointer(d, root, &r, &r, &root_x, &root_y, &win_x, &win_y, &mask);
998 if (res) break;
1000 if (!res) {
1001 fprintf(stderr, "No mouse found.\n");
1002 root_x = 0;
1003 root_y = 0;
1006 // now find in which monitor the mice is on
1007 int monitors;
1008 XineramaScreenInfo *info = XineramaQueryScreens(d, &monitors);
1009 if (info) {
1010 for (int i = 0; i < monitors; ++i) {
1011 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
1012 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
1013 offset_x = info[i].x_org;
1014 offset_y = info[i].y_org;
1015 d_width = info[i].width;
1016 d_height = info[i].height;
1017 break;
1021 XFree(info);
1023 #endif
1025 Colormap cmap = DefaultColormap(d, DefaultScreen(d));
1026 XColor p_fg, p_bg,
1027 compl_fg, compl_bg,
1028 compl_highlighted_fg, compl_highlighted_bg,
1029 border_n_bg, border_e_bg, border_s_bg, border_w_bg;
1031 bool horizontal_layout = true;
1033 // read resource
1034 XrmInitialize();
1035 char *xrm = XResourceManagerString(d);
1036 XrmDatabase xdb = nil;
1037 if (xrm != nil) {
1038 xdb = XrmGetStringDatabase(xrm);
1039 XrmValue value;
1040 char *datatype[20];
1042 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
1043 fontname = strdup(value.addr);
1044 check_allocation(fontname);
1045 } else {
1046 fprintf(stderr, "no font defined, using %s\n", fontname);
1049 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == true)
1050 horizontal_layout = !strcmp(value.addr, "horizontal");
1051 else
1052 fprintf(stderr, "no layout defined, using horizontal\n");
1054 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == true) {
1055 free(ps1);
1056 ps1 = normalize_str(value.addr);
1057 } else {
1058 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", ps1);
1061 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
1062 width = parse_int_with_percentage(value.addr, width, d_width);
1063 else
1064 fprintf(stderr, "no width defined, using %d\n", width);
1066 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
1067 height = parse_int_with_percentage(value.addr, height, d_height);
1068 else
1069 fprintf(stderr, "no height defined, using %d\n", height);
1071 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
1072 x = parse_int_with_pos(value.addr, x, d_width, width);
1073 else
1074 fprintf(stderr, "no x defined, using %d\n", x);
1076 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
1077 y = parse_int_with_pos(value.addr, y, d_height, height);
1078 else
1079 fprintf(stderr, "no y defined, using %d\n", y);
1081 if (XrmGetResource(xdb, "MyMenu.padding", "*", datatype, &value) == true)
1082 padding = parse_integer(value.addr, padding);
1083 else
1084 fprintf(stderr, "no padding defined, using %d\n", padding);
1086 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value) == true) {
1087 char **borders = parse_csslike(value.addr);
1088 if (borders != nil) {
1089 border_n = parse_integer(borders[0], 0);
1090 border_e = parse_integer(borders[1], 0);
1091 border_s = parse_integer(borders[2], 0);
1092 border_w = parse_integer(borders[3], 0);
1093 } else {
1094 fprintf(stderr, "error while parsing MyMenu.border.size\n");
1096 } else {
1097 fprintf(stderr, "no border defined, using 0.\n");
1100 XColor tmp;
1101 // TODO: tmp needs to be free'd after every allocation?
1103 // prompt
1104 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
1105 XAllocNamedColor(d, cmap, value.addr, &p_fg, &tmp);
1106 else
1107 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
1109 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
1110 XAllocNamedColor(d, cmap, value.addr, &p_bg, &tmp);
1111 else
1112 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
1114 // completion
1115 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
1116 XAllocNamedColor(d, cmap, value.addr, &compl_fg, &tmp);
1117 else
1118 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
1120 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
1121 XAllocNamedColor(d, cmap, value.addr, &compl_bg, &tmp);
1122 else
1123 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
1125 // completion highlighted
1126 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
1127 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_fg, &tmp);
1128 else
1129 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
1131 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
1132 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_bg, &tmp);
1133 else
1134 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
1136 // border
1137 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value) == true) {
1138 char **colors = parse_csslike(value.addr);
1139 if (colors != nil) {
1140 XAllocNamedColor(d, cmap, colors[0], &border_n_bg, &tmp);
1141 XAllocNamedColor(d, cmap, colors[1], &border_e_bg, &tmp);
1142 XAllocNamedColor(d, cmap, colors[2], &border_s_bg, &tmp);
1143 XAllocNamedColor(d, cmap, colors[3], &border_w_bg, &tmp);
1144 } else {
1145 fprintf(stderr, "error while parsing MyMenu.border.color\n");
1147 } else {
1148 XAllocNamedColor(d, cmap, "white", &border_n_bg, &tmp);
1149 XAllocNamedColor(d, cmap, "white", &border_e_bg, &tmp);
1150 XAllocNamedColor(d, cmap, "white", &border_s_bg, &tmp);
1151 XAllocNamedColor(d, cmap, "white", &border_w_bg, &tmp);
1153 } else {
1154 XColor tmp;
1155 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
1156 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
1157 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
1158 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
1159 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
1160 XAllocNamedColor(d, cmap, "white", &border_n_bg, &tmp);
1161 XAllocNamedColor(d, cmap, "white", &border_e_bg, &tmp);
1162 XAllocNamedColor(d, cmap, "white", &border_s_bg, &tmp);
1163 XAllocNamedColor(d, cmap, "white", &border_w_bg, &tmp);
1166 // second round of args parsing
1167 optind = 0; // reset the option index
1168 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1169 switch (ch) {
1170 case 'a':
1171 first_selected = true;
1172 break;
1173 case 'e':
1174 // (embedding mymenu) this case was already catched.
1175 break;
1176 case 'p': {
1177 char *newprompt = strdup(optarg);
1178 if (newprompt != nil) {
1179 free(ps1);
1180 ps1 = newprompt;
1182 break;
1184 case 'x':
1185 x = parse_int_with_pos(optarg, x, d_width, width);
1186 break;
1187 case 'y':
1188 y = parse_int_with_pos(optarg, y, d_height, height);
1189 break;
1190 case 'P':
1191 padding = parse_integer(optarg, padding);
1192 break;
1193 case 'l':
1194 horizontal_layout = !strcmp(optarg, "horizontal");
1195 break;
1196 case 'f': {
1197 char *newfont = strdup(optarg);
1198 if (newfont != nil) {
1199 free(fontname);
1200 fontname = newfont;
1202 break;
1204 case 'W':
1205 width = parse_int_with_percentage(optarg, width, d_width);
1206 break;
1207 case 'H':
1208 height = parse_int_with_percentage(optarg, height, d_height);
1209 break;
1210 case 'b': {
1211 char **borders = parse_csslike(optarg);
1212 if (borders != nil) {
1213 border_n = parse_integer(borders[0], 0);
1214 border_e = parse_integer(borders[1], 0);
1215 border_s = parse_integer(borders[2], 0);
1216 border_w = parse_integer(borders[3], 0);
1217 } else {
1218 fprintf(stderr, "Error parsing b option\n");
1220 break;
1222 case 'B': {
1223 char **colors = parse_csslike(optarg);
1224 if (colors != nil) {
1225 XColor tmp;
1226 XAllocNamedColor(d, cmap, colors[0], &border_n_bg, &tmp);
1227 XAllocNamedColor(d, cmap, colors[1], &border_e_bg, &tmp);
1228 XAllocNamedColor(d, cmap, colors[2], &border_s_bg, &tmp);
1229 XAllocNamedColor(d, cmap, colors[3], &border_w_bg, &tmp);
1230 } else {
1231 fprintf(stderr, "error while parsing B option\n");
1233 break;
1235 case 't': {
1236 XColor tmp;
1237 XAllocNamedColor(d, cmap, optarg, &p_fg, &tmp);
1238 break;
1240 case 'T': {
1241 XColor tmp;
1242 XAllocNamedColor(d, cmap, optarg, &p_bg, &tmp);
1243 break;
1245 case 'c': {
1246 XColor tmp;
1247 XAllocNamedColor(d, cmap, optarg, &compl_fg, &tmp);
1248 break;
1250 case 'C': {
1251 XColor tmp;
1252 XAllocNamedColor(d, cmap, optarg, &compl_bg, &tmp);
1253 break;
1255 case 's': {
1256 XColor tmp;
1257 XAllocNamedColor(d, cmap, optarg, &compl_highlighted_fg, &tmp);
1258 break;
1260 case 'S': {
1261 XColor tmp;
1262 XAllocNamedColor(d, cmap, optarg, &compl_highlighted_bg, &tmp);
1263 break;
1265 default:
1266 fprintf(stderr, "Unrecognized option %c\n", ch);
1267 status = ERR;
1268 break;
1272 // since only now we know if the first should be selected, update
1273 // the completion here
1274 update_completions(cs, text, lines, first_selected);
1276 // load the font
1277 #ifdef USE_XFT
1278 XftFont *font = XftFontOpenName(d, DefaultScreen(d), fontname);
1279 #else
1280 char **missing_charset_list;
1281 int missing_charset_count;
1282 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
1283 if (font == nil) {
1284 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1285 return EX_UNAVAILABLE;
1287 #endif
1289 // create the window
1290 XSetWindowAttributes attr;
1291 attr.override_redirect = true;
1292 attr.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
1294 Window w = XCreateWindow(d, // display
1295 parent_window, // parent
1296 x + offset_x, y + offset_y, // x y
1297 width, height, // w h
1298 0, // border width
1299 CopyFromParent, // depth
1300 InputOutput, // class
1301 CopyFromParent, // visual
1302 CWEventMask | CWOverrideRedirect, // value mask (CWBackPixel in the future also?)
1303 &attr);
1305 set_win_atoms_hints(d, w, width, height);
1307 // we want some events
1308 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeymapStateMask);
1309 XMapRaised(d, w);
1311 // if embed, listen for other events as well
1312 if (embed) {
1313 XSelectInput(d, parent_window, FocusChangeMask);
1314 Window *children, parent, root;
1315 unsigned int children_no;
1316 if (XQueryTree(d, parent_window, &root, &parent, &children, &children_no) && children) {
1317 for (unsigned int i = 0; i < children_no && children[i] != w; ++i)
1318 XSelectInput(d, children[i], FocusChangeMask);
1319 XFree(children);
1321 grabfocus(d, w);
1324 // grab keyboard
1325 take_keyboard(d, w);
1327 // Create some graphics contexts
1328 XGCValues values;
1329 /* values.font = font->fid; */
1331 struct rendering r = {
1332 .d = d,
1333 .w = w,
1334 .width = width,
1335 .height = height,
1336 .padding = padding,
1337 .x_zero = border_w,
1338 .y_zero = border_n,
1339 .border_n = border_n,
1340 .border_e = border_e,
1341 .border_s = border_s,
1342 .border_w = border_w,
1343 .horizontal_layout = horizontal_layout,
1344 .ps1 = ps1,
1345 .ps1len = strlen(ps1),
1346 .prompt = XCreateGC(d, w, 0, &values),
1347 .prompt_bg = XCreateGC(d, w, 0, &values),
1348 .completion = XCreateGC(d, w, 0, &values),
1349 .completion_bg = XCreateGC(d, w, 0, &values),
1350 .completion_highlighted = XCreateGC(d, w, 0, &values),
1351 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
1352 .border_n_bg = XCreateGC(d, w, 0, &values),
1353 .border_e_bg = XCreateGC(d, w, 0, &values),
1354 .border_s_bg = XCreateGC(d, w, 0, &values),
1355 .border_w_bg = XCreateGC(d, w, 0, &values),
1356 #ifdef USE_XFT
1357 .font = font,
1358 #else
1359 .font = &font,
1360 #endif
1363 #ifdef USE_XFT
1364 r.xftdraw = XftDrawCreate(d, w, DefaultVisual(d, 0), DefaultColormap(d, 0));
1366 // prompt
1367 XRenderColor xrcolor;
1368 xrcolor.red = p_fg.red;
1369 xrcolor.green = p_fg.red;
1370 xrcolor.blue = p_fg.red;
1371 xrcolor.alpha = 65535;
1372 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_prompt);
1374 // completion
1375 xrcolor.red = compl_fg.red;
1376 xrcolor.green = compl_fg.green;
1377 xrcolor.blue = compl_fg.blue;
1378 xrcolor.alpha = 65535;
1379 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion);
1381 // completion highlighted
1382 xrcolor.red = compl_highlighted_fg.red;
1383 xrcolor.green = compl_highlighted_fg.green;
1384 xrcolor.blue = compl_highlighted_fg.blue;
1385 xrcolor.alpha = 65535;
1386 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion_highlighted);
1387 #endif
1389 // load the colors in our GCs
1390 XSetForeground(d, r.prompt, p_fg.pixel);
1391 XSetForeground(d, r.prompt_bg, p_bg.pixel);
1392 XSetForeground(d, r.completion, compl_fg.pixel);
1393 XSetForeground(d, r.completion_bg, compl_bg.pixel);
1394 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel);
1395 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg.pixel);
1396 XSetForeground(d, r.border_n_bg, border_n_bg.pixel);
1397 XSetForeground(d, r.border_e_bg, border_e_bg.pixel);
1398 XSetForeground(d, r.border_s_bg, border_s_bg.pixel);
1399 XSetForeground(d, r.border_w_bg, border_w_bg.pixel);
1401 // open the X input method
1402 XIM xim = XOpenIM(d, xdb, resname, resclass);
1403 check_allocation(xim);
1405 XIMStyles *xis = nil;
1406 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1407 fprintf(stderr, "Input Styles could not be retrieved\n");
1408 return EX_UNAVAILABLE;
1411 XIMStyle bestMatchStyle = 0;
1412 for (int i = 0; i < xis->count_styles; ++i) {
1413 XIMStyle ts = xis->supported_styles[i];
1414 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1415 bestMatchStyle = ts;
1416 break;
1419 XFree(xis);
1421 if (!bestMatchStyle) {
1422 fprintf(stderr, "No matching input style could be determined\n");
1425 XIC xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
1426 check_allocation(xic);
1428 // draw the window for the first time
1429 draw(&r, text, cs);
1431 // main loop
1432 while (status == LOOPING) {
1433 XEvent e;
1434 XNextEvent(d, &e);
1436 if (XFilterEvent(&e, w))
1437 continue;
1439 switch (e.type) {
1440 case KeymapNotify:
1441 XRefreshKeyboardMapping(&e.xmapping);
1442 break;
1444 case FocusIn:
1445 // re-grab focus
1446 if (e.xfocus.window != w)
1447 grabfocus(d, w);
1448 break;
1450 case VisibilityNotify:
1451 if (e.xvisibility.state != VisibilityUnobscured)
1452 XRaiseWindow(d, w);
1453 break;
1455 case MapNotify:
1456 /* fprintf(stderr, "Map Notify!\n"); */
1457 /* TODO: update the computed window and height! */
1458 /* get_wh(d, &w, width, height); */
1459 draw(&r, text, cs);
1460 break;
1462 case KeyPress: {
1463 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
1465 char *input;
1466 switch (parse_event(d, ev, xic, &input)) {
1467 case EXIT:
1468 status = ERR;
1469 break;
1471 case CONFIRM:
1472 status = OK;
1474 // if first_selected is active and the first completion is
1475 // active be sure to 'expand' the text to match the selection
1476 if (first_selected && cs && cs->selected == 0) {
1477 free(text);
1478 text = strdup(cs->completions->completion);
1479 if (text == nil) {
1480 fprintf(stderr, "Memory allocation error");
1481 status = ERR;
1483 textlen = strlen(text);
1485 break;
1487 case PREV_COMPL: {
1488 complete(cs, first_selected, true, &text, &textlen, &status);
1489 break;
1492 case NEXT_COMPL: {
1493 complete(cs, first_selected, false, &text, &textlen, &status);
1494 break;
1497 case DEL_CHAR:
1498 popc(text);
1499 update_completions(cs, text, lines, first_selected);
1500 break;
1502 case DEL_WORD: {
1503 popw(text);
1504 update_completions(cs, text, lines, first_selected);
1505 break;
1508 case DEL_LINE: {
1509 for (int i = 0; i < textlen; ++i)
1510 text[i] = 0;
1511 update_completions(cs, text, lines, first_selected);
1512 break;
1515 case ADD_CHAR: {
1516 int str_len = strlen(input);
1518 // sometimes a strange key is pressed (i.e. ctrl alone),
1519 // so input will be empty. Don't need to update completion
1520 // in this case
1521 if (str_len == 0)
1522 break;
1524 for (int i = 0; i < str_len; ++i) {
1525 textlen = pushc(&text, textlen, input[i]);
1526 if (textlen == -1) {
1527 fprintf(stderr, "Memory allocation error\n");
1528 status = ERR;
1529 break;
1532 if (status != ERR) {
1533 update_completions(cs, text, lines, first_selected);
1534 free(input);
1536 break;
1539 case TOGGLE_FIRST_SELECTED:
1540 first_selected = !first_selected;
1541 if (first_selected && cs->selected < 0)
1542 cs->selected = 0;
1543 if (!first_selected && cs->selected == 0)
1544 cs->selected = -1;
1545 break;
1550 draw(&r, text, cs);
1553 if (status == OK)
1554 printf("%s\n", text);
1556 release_keyboard(r.d);
1558 #ifdef USE_XFT
1559 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_prompt);
1560 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion);
1561 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion_highlighted);
1562 #endif
1564 free(ps1);
1565 free(fontname);
1566 free(text);
1568 char *l = nil;
1569 char **lns = lines;
1570 while ((l = *lns) != nil) {
1571 free(l);
1572 ++lns;
1575 free(lines);
1576 compls_delete(cs);
1578 XDestroyWindow(r.d, r.w);
1579 XCloseDisplay(r.d);
1581 return status;