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:d:A"
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 char *rcompletion;
138 struct completion *next;
139 };
141 // Wrap the linked list of completions
142 struct completions {
143 struct completion *completions;
144 int selected;
145 int lenght;
146 };
148 // return a newly allocated (and empty) completion list
149 struct completions *compls_new() {
150 struct completions *cs = malloc(sizeof(struct completions));
152 if (cs == nil)
153 return cs;
155 cs->completions = nil;
156 cs->selected = -1;
157 cs->lenght = 0;
158 return cs;
161 // Return a newly allocated (and empty) completion
162 struct completion *compl_new() {
163 struct completion *c = malloc(sizeof(struct completion));
164 if (c == nil)
165 return c;
167 c->completion = nil;
168 c->rcompletion = nil;
169 c->next = nil;
170 return c;
173 // delete ONLY the given completion (i.e. does not free c->next...)
174 void compl_delete(struct completion *c) {
175 free(c);
178 // delete the current completion and the next (c->next) and so on...
179 void compl_delete_rec(struct completion *c) {
180 while (c != nil) {
181 struct completion *t = c->next;
182 free(c);
183 c = t;
187 // Delete the wrapper and the whole list
188 void compls_delete(struct completions *cs) {
189 if (cs == nil)
190 return;
192 compl_delete_rec(cs->completions);
193 free(cs);
196 // create a completion list from a text and the list of possible
197 // completions (null terminated). Expects a non-null `cs'. lines and
198 // vlines should have the same lenght OR vlines is null
199 void filter(struct completions *cs, char *text, char **lines, char **vlines) {
200 struct completion *c = compl_new();
201 if (c == nil) {
202 return;
205 cs->completions = c;
207 int index = 0;
208 int matching = 0;
210 if (vlines == nil)
211 vlines = lines;
213 while (true) {
214 char *l = vlines[index] ? vlines[index] : lines[index];
215 if (l == nil)
216 break;
218 if (strcasestr(l, text) != nil) {
219 matching++;
221 c->next = compl_new();
222 c = c->next;
223 if (c == nil) {
224 compls_delete(cs);
225 return;
227 c->completion = l;
228 c->rcompletion = lines[index];
231 index++;
234 struct completion *f = cs->completions->next;
235 compl_delete(cs->completions);
236 cs->completions = f;
237 cs->lenght = matching;
238 cs->selected = -1;
241 // update the given completion, that is: clean the old cs & generate a new one.
242 void update_completions(struct completions *cs, char *text, char **lines, char **vlines, bool first_selected) {
243 compl_delete_rec(cs->completions);
244 filter(cs, text, lines, vlines);
245 if (first_selected && cs->lenght > 0)
246 cs->selected = 0;
249 // select the next, or the previous, selection and update some
250 // state. `text' will be updated with the text of the completion and
251 // `textlen' with the new lenght of `text'. If the memory cannot be
252 // allocated, `status' will be set to `ERR'.
253 void complete(struct completions *cs, bool first_selected, bool p, char **text, int *textlen, enum state *status) {
254 if (cs == nil || cs->lenght == 0)
255 return;
257 // if the first is always selected, and the first entry is different
258 // from the text, expand the text and return
259 if (first_selected
260 && cs->selected == 0
261 && strcmp(cs->completions->completion, *text) != 0
262 && !p) {
263 free(*text);
264 *text = strdup(cs->completions->completion);
265 if (text == nil) {
266 *status = ERR;
267 return;
269 *textlen = strlen(*text);
270 return;
273 int index = cs->selected;
275 if (index == -1 && p)
276 index = 0;
277 index = cs->selected = (cs->lenght + (p ? index - 1 : index + 1)) % cs->lenght;
279 struct completion *n = cs->completions;
281 // find the selected item
282 while (index != 0) {
283 index--;
284 n = n->next;
287 free(*text);
288 *text = strdup(n->completion);
289 if (text == nil) {
290 fprintf(stderr, "Memory allocation error!\n");
291 *status = ERR;
292 return;
294 *textlen = strlen(*text);
297 // push the character c at the end of the string pointed by p
298 int pushc(char **p, int maxlen, char c) {
299 int len = strnlen(*p, maxlen);
301 if (!(len < maxlen -2)) {
302 maxlen += maxlen >> 1;
303 char *newptr = realloc(*p, maxlen);
304 if (newptr == nil) { // bad!
305 return -1;
307 *p = newptr;
310 (*p)[len] = c;
311 (*p)[len+1] = '\0';
312 return maxlen;
315 // remove the last rune from the *utf8* string! This is different from
316 // just setting the last byte to 0 (in some cases ofc). Return a
317 // pointer (e) to the last non zero char. If e < p then p is empty!
318 char* popc(char *p) {
319 int len = strlen(p);
320 if (len == 0)
321 return p;
323 char *e = p + len - 1;
325 do {
326 char c = *e;
327 *e = 0;
328 e--;
330 // if c is a starting byte (11......) or is under U+007F (ascii,
331 // basically) we're done
332 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
333 break;
334 } while (e >= p);
336 return e;
339 // remove the last word plus trailing whitespaces from the give string
340 void popw(char *w) {
341 int len = strlen(w);
342 if (len == 0)
343 return;
345 bool in_word = true;
346 while (true) {
347 char *e = popc(w);
349 if (e < w)
350 return;
352 if (in_word && isspace(*e))
353 in_word = false;
355 if (!in_word && !isspace(*e))
356 return;
360 // If the string is surrounded by quotes (`"`) remove them and replace
361 // every `\"` in the string with `"`
362 char *normalize_str(const char *str) {
363 int len = strlen(str);
364 if (len == 0)
365 return nil;
367 char *s = calloc(len, sizeof(char));
368 check_allocation(s);
369 int p = 0;
370 while (*str) {
371 char c = *str;
372 if (*str == '\\') {
373 if (*(str + 1)) {
374 s[p] = *(str + 1);
375 p++;
376 str += 2; // skip this and the next char
377 continue;
378 } else {
379 break;
382 if (c == '"') {
383 str++; // skip only this char
384 continue;
386 s[p] = c;
387 p++;
388 str++;
390 return s;
393 // read an arbitrary long line from stdin and return a pointer to it
394 // TODO: resize the allocated memory to exactly fit the string once
395 // read?
396 char *readline(bool *eof) {
397 int maxlen = 8;
398 char *str = calloc(maxlen, sizeof(char));
399 if (str == nil) {
400 fprintf(stderr, "Cannot allocate memory!\n");
401 exit(EX_UNAVAILABLE);
404 int c;
405 while((c = getchar()) != EOF) {
406 if (c == '\n')
407 return str;
408 else
409 maxlen = pushc(&str, maxlen, c);
411 if (maxlen == -1) {
412 fprintf(stderr, "Cannot allocate memory!\n");
413 exit(EX_UNAVAILABLE);
416 *eof = true;
417 return str;
420 // read an arbitrary amount of text until an EOF and store it in
421 // lns. `items` is the capacity of lns. It may increase lns with
422 // `realloc(3)` to store more line. Return the number of lines
423 // read. The last item will always be a NULL pointer. It ignore the
424 // "null" (empty) lines
425 int readlines(char ***lns, int items) {
426 bool finished = false;
427 int n = 0;
428 char **lines = *lns;
429 while (true) {
430 lines[n] = readline(&finished);
432 if (strlen(lines[n]) == 0 || lines[n][0] == '\n') {
433 free(lines[n]);
434 --n; // forget about this line
437 if (finished)
438 break;
440 ++n;
442 if (n == items - 1) {
443 items += items >>1;
444 char **l = realloc(lines, sizeof(char*) * items);
445 check_allocation(l);
446 *lns = l;
447 lines = l;
451 n++;
452 lines[n] = nil;
453 return items;
456 // Compute the dimension of the string str once rendered, return the
457 // width and save the width and the height in ret_width and ret_height
458 int text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height) {
459 int height;
460 int width;
461 #ifdef USE_XFT
462 XGlyphInfo gi;
463 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
464 /* height = gi.height; */
465 /* height = (gi.height + (r->font->ascent - r->font->descent)/2) / 2; */
466 /* height = (r->font->ascent - r->font->descent)/2 + gi.height*2; */
467 height = r->font->ascent - r->font->descent;
468 width = gi.width - gi.x;
469 #else
470 XRectangle rect;
471 XmbTextExtents(*r->font, str, len, nil, &rect);
472 height = rect.height;
473 width = rect.width;
474 #endif
475 if (ret_width != nil) *ret_width = width;
476 if (ret_height != nil) *ret_height = height;
477 return width;
480 // Draw the string str
481 void draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt) {
482 #ifdef USE_XFT
483 XftColor xftcolor;
484 if (tt == PROMPT) xftcolor = r->xft_prompt;
485 if (tt == COMPL) xftcolor = r->xft_completion;
486 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
488 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
489 #else
490 GC gc;
491 if (tt == PROMPT) gc = r->prompt;
492 if (tt == COMPL) gc = r->completion;
493 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
494 Xutf8DrawString(r->d, r->w, *r->font, gc, x, y, str, len);
495 #endif
498 // Duplicate the string str and substitute every space with a 'n'
499 char *strdupn(char *str) {
500 int len = strlen(str);
502 if (str == nil || len == 0)
503 return nil;
505 char *dup = strdup(str);
506 if (dup == nil)
507 return nil;
509 for (int i = 0; i < len; ++i)
510 if (dup[i] == ' ')
511 dup[i] = 'n';
513 return dup;
516 // |------------------|----------------------------------------------|
517 // | 20 char text | completion | completion | completion | compl |
518 // |------------------|----------------------------------------------|
519 void draw_horizontally(struct rendering *r, char *text, struct completions *cs) {
520 int prompt_width = 20; // char
522 int width, height;
523 int ps1xlen = text_extents(r->ps1, r->ps1len, r, &width, &height);
524 int start_at = ps1xlen;
526 start_at = r->x_zero + text_extents("n", 1, r, nil, nil);
527 start_at = start_at * prompt_width + r->padding;
529 int texty = (inner_height(r) + height + r->y_zero) / 2;
531 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, start_at, inner_height(r));
533 int text_len = strlen(text);
534 if (text_len > prompt_width)
535 text = text + (text_len - prompt_width);
536 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, texty, r, PROMPT);
537 draw_string(text, MIN(text_len, prompt_width), r->x_zero + r->padding + ps1xlen, texty, r, PROMPT);
539 XFillRectangle(r->d, r->w, r->completion_bg, start_at, r->y_zero, r->width, inner_height(r));
541 struct completion *c = cs->completions;
542 for (int i = 0; c != nil; ++i) {
543 enum text_type tt = cs->selected == i ? COMPL_HIGH : COMPL;
544 GC h = cs->selected == i ? r->completion_highlighted_bg : r->completion_bg;
546 int len = strlen(c->completion);
547 int text_width = text_extents(c->completion, len, r, nil, nil);
549 XFillRectangle(r->d, r->w, h, start_at, r->y_zero, text_width + r->padding*2, inner_height(r));
551 draw_string(c->completion, len, start_at + r->padding, texty, r, tt);
553 start_at += text_width + r->padding * 2;
555 if (start_at > inner_width(r))
556 break; // don't draw completion if the space isn't enough
558 c = c->next;
562 // |-----------------------------------------------------------------|
563 // | prompt |
564 // |-----------------------------------------------------------------|
565 // | completion |
566 // |-----------------------------------------------------------------|
567 // | completion |
568 // |-----------------------------------------------------------------|
569 void draw_vertically(struct rendering *r, char *text, struct completions *cs) {
570 int height, width;
571 text_extents("fjpgl", 5, r, nil, &height);
572 int start_at = height + r->padding;
574 XFillRectangle(r->d, r->w, r->completion_bg, r->x_zero, r->y_zero, r->width, r->height);
575 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, r->width, start_at);
577 int ps1xlen = text_extents(r->ps1, r->ps1len, r, nil, nil);
579 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, r->y_zero + height + r->padding, r, PROMPT);
580 draw_string(text, strlen(text), r->x_zero + r->padding + ps1xlen, r->y_zero + height + r->padding, r, PROMPT);
582 start_at += r->padding + r->y_zero;
584 struct completion *c = cs->completions;
585 for (int i = 0; c != nil; ++i){
586 enum text_type tt = cs->selected == i ? COMPL_HIGH : COMPL;
587 GC h = cs->selected == i ? r->completion_highlighted_bg : r->completion_bg;
589 int len = strlen(c->completion);
590 text_extents(c->completion, len, r, &width, &height);
591 XFillRectangle(r->d, r->w, h, r->x_zero, start_at, inner_width(r), height + r->padding*2);
592 draw_string(c->completion, len, r->x_zero + r->padding, start_at + height + r->padding, r, tt);
594 start_at += height + r->padding *2;
596 if (start_at > inner_height(r))
597 break; // don't draw completion if the space isn't enough
599 c = c->next;
603 void draw(struct rendering *r, char *text, struct completions *cs) {
604 if (r->horizontal_layout)
605 draw_horizontally(r, text, cs);
606 else
607 draw_vertically(r, text, cs);
609 // draw the borders
611 if (r->border_w != 0)
612 XFillRectangle(r->d, r->w, r->border_w_bg, 0, 0, r->border_w, r->height);
614 if (r->border_e != 0)
615 XFillRectangle(r->d, r->w, r->border_e_bg, r->width - r->border_e, 0, r->border_e, r->height);
617 if (r->border_n != 0)
618 XFillRectangle(r->d, r->w, r->border_n_bg, 0, 0, r->width, r->border_n);
620 if (r->border_s != 0)
621 XFillRectangle(r->d, r->w, r->border_s_bg, 0, r->height - r->border_s, r->width, r->border_s);
623 // send all the work to x
624 XFlush(r->d);
627 /* Set some WM stuff */
628 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
629 Atom type;
630 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
631 XChangeProperty(
632 d,
633 w,
634 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
635 XInternAtom(d, "ATOM", false),
636 32,
637 PropModeReplace,
638 (unsigned char *)&type,
640 );
642 /* some window managers honor this properties */
643 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
644 XChangeProperty(d,
645 w,
646 XInternAtom(d, "_NET_WM_STATE", false),
647 XInternAtom(d, "ATOM", false),
648 32,
649 PropModeReplace,
650 (unsigned char *)&type,
652 );
654 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
655 XChangeProperty(d,
656 w,
657 XInternAtom(d, "_NET_WM_STATE", false),
658 XInternAtom(d, "ATOM", false),
659 32,
660 PropModeAppend,
661 (unsigned char *)&type,
663 );
665 // setting window hints
666 XClassHint *class_hint = XAllocClassHint();
667 if (class_hint == nil) {
668 fprintf(stderr, "Could not allocate memory for class hint\n");
669 exit(EX_UNAVAILABLE);
671 class_hint->res_name = resname;
672 class_hint->res_class = resclass;
673 XSetClassHint(d, w, class_hint);
674 XFree(class_hint);
676 XSizeHints *size_hint = XAllocSizeHints();
677 if (size_hint == nil) {
678 fprintf(stderr, "Could not allocate memory for size hint\n");
679 exit(EX_UNAVAILABLE);
681 size_hint->flags = PMinSize | PBaseSize;
682 size_hint->min_width = width;
683 size_hint->base_width = width;
684 size_hint->min_height = height;
685 size_hint->base_height = height;
687 XFlush(d);
690 // write the width and height of the window `w' respectively in `width'
691 // and `height'.
692 void get_wh(Display *d, Window *w, int *width, int *height) {
693 XWindowAttributes win_attr;
694 XGetWindowAttributes(d, *w, &win_attr);
695 *height = win_attr.height;
696 *width = win_attr.width;
699 int grabfocus(Display *d, Window w) {
700 for (int i = 0; i < 100; ++i) {
701 Window focuswin;
702 int revert_to_win;
703 XGetInputFocus(d, &focuswin, &revert_to_win);
704 if (focuswin == w)
705 return true;
706 XSetInputFocus(d, w, RevertToParent, CurrentTime);
707 usleep(1000);
709 return 0;
712 // I know this may seem a little hackish BUT is the only way I managed
713 // to actually grab that goddam keyboard. Only one call to
714 // XGrabKeyboard does not always end up with the keyboard grabbed!
715 int take_keyboard(Display *d, Window w) {
716 int i;
717 for (i = 0; i < 100; i++) {
718 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
719 return 1;
720 usleep(1000);
722 fprintf(stderr, "Cannot grab keyboard\n");
723 return 0;
726 // release the keyboard.
727 void release_keyboard(Display *d) {
728 XUngrabKeyboard(d, CurrentTime);
731 // Given a string, try to parse it as a number or return
732 // `default_value'.
733 int parse_integer(const char *str, int default_value) {
734 errno = 0;
735 char *ep;
736 long lval = strtol(str, &ep, 10);
737 if (str[0] == '\0' || *ep != '\0') { // NaN
738 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
739 return default_value;
741 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
742 (lval > INT_MAX || lval < INT_MIN)) {
743 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
744 return default_value;
746 return lval;
749 // like parse_integer, but if the value ends with a `%' then its
750 // treated like a percentage (`max' is used to compute the percentage)
751 int parse_int_with_percentage(const char *str, int default_value, int max) {
752 int len = strlen(str);
753 if (len > 0 && str[len-1] == '%') {
754 char *cpy = strdup(str);
755 check_allocation(cpy);
756 cpy[len-1] = '\0';
757 int val = parse_integer(cpy, default_value);
758 free(cpy);
759 return val * max / 100;
761 return parse_integer(str, default_value);
764 // like parse_int_with_percentage but understands some special values
765 // - "middle" that is (max - self) / 2
766 // - "start" that is 0
767 // - "end" that is (max - self)
768 int parse_int_with_pos(const char *str, int default_value, int max, int self) {
769 if (!strcmp(str, "start"))
770 return 0;
771 if (!strcmp(str, "middle"))
772 return (max - self)/2;
773 if (!strcmp(str, "end"))
774 return max-self;
775 return parse_int_with_percentage(str, default_value, max);
778 // parse a string like a css value (for example like the css
779 // margin/padding properties). Will ALWAYS return an array of 4 word
780 // TODO: harden this function!
781 char **parse_csslike(const char *str) {
782 char *s = strdup(str);
783 if (s == nil)
784 return nil;
786 char **ret = malloc(4 * sizeof(char*));
787 if (ret == nil) {
788 free(s);
789 return nil;
792 int i = 0;
793 char *token;
794 while ((token = strsep(&s, " ")) != NULL && i < 4) {
795 ret[i] = strdup(token);
796 i++;
799 if (i == 1)
800 for (int j = 1; j < 4; j++)
801 ret[j] = strdup(ret[0]);
803 if (i == 2) {
804 ret[2] = strdup(ret[0]);
805 ret[3] = strdup(ret[1]);
808 if (i == 3)
809 ret[3] = strdup(ret[1]);
811 // Before we didn't check for the return type of strdup, here we will
813 bool any_null = false;
814 for (int i = 0; i < 4; ++i)
815 any_null = ret[i] == nil || any_null;
817 if (any_null)
818 for (int i = 0; i < 4; ++i)
819 if (ret[i] != nil)
820 free(ret[i]);
822 if (i == 0 || any_null) {
823 free(s);
824 free(ret);
825 return nil;
828 return ret;
831 // Given an event, try to understand what the user wants. If the
832 // return value is ADD_CHAR then `input' is a pointer to a string that
833 // will need to be free'ed.
834 enum action parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input) {
835 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
836 return DEL_CHAR;
838 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
839 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
841 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
842 return CONFIRM;
844 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
845 return EXIT;
847 // try to read what the user pressed
848 char str[SYM_BUF_SIZE] = {0};
849 Status s = 0;
850 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
851 if (s == XBufferOverflow) {
852 // should not happen since there are no utf-8 characters larger
853 // than 24bits
854 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
855 return EXIT;
858 if (ev->state & ControlMask) {
859 if (!strcmp(str, "")) // C-u
860 return DEL_LINE;
861 if (!strcmp(str, "")) // C-w
862 return DEL_WORD;
863 if (!strcmp(str, "")) // C-h
864 return DEL_CHAR;
865 if (!strcmp(str, "\r")) // C-m
866 return CONFIRM;
867 if (!strcmp(str, "")) // C-p
868 return PREV_COMPL;
869 if (!strcmp(str, "")) // C-n
870 return NEXT_COMPL;
871 if (!strcmp(str, "")) // C-c
872 return EXIT;
873 if (!strcmp(str, "\t")) // C-i
874 return TOGGLE_FIRST_SELECTED;
877 *input = strdup(str);
878 if (*input == nil) {
879 fprintf(stderr, "Error while allocating memory for key.\n");
880 return EXIT;
883 return ADD_CHAR;
886 // Given the name of the program (argv[0]?) print a small help on stderr
887 void usage(char *prgname) {
888 fprintf(stderr, "%s [-hva] [-p prompt] [-x coord] [-y coord] [-W width] [-H height]\n"
889 " [-P padding] [-l layout] [-f font] [-b borders] [-B colors]\n"
890 " [-t color] [-T color] [-c color] [-C color] [-s color] [-S color]\n"
891 " [-w window_id]\n", prgname);
894 int main(int argc, char **argv) {
895 #ifdef HAVE_PLEDGE
896 // stdio & rpat: to read and write stdio/stdout
897 // unix: to connect to Xorg
898 pledge("stdio rpath unix", "");
899 #endif
901 char *sep = nil;
903 // by default the first completion isn't selected
904 bool first_selected = false;
906 // our parent window
907 char *parent_window_id = nil;
909 // the user can input arbitrary text
910 bool free_text = true;
912 // first round of args parsing
913 int ch;
914 while ((ch = getopt(argc, argv, ARGS)) != -1) {
915 switch (ch) {
916 case 'h': // help
917 usage(*argv);
918 return 0;
919 case 'v': // version
920 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
921 return 0;
922 case 'e': // embed
923 parent_window_id = strdup(optarg);
924 check_allocation(parent_window_id);
925 break;
926 case 'd': {
927 sep = strdup(optarg);
928 check_allocation(sep);
930 case 'A': {
931 free_text = false;
932 break;
934 default:
935 break;
939 // read the lines from stdin
940 char **lines = calloc(INITIAL_ITEMS, sizeof(char*));
941 check_allocation(lines);
942 int nlines = readlines(&lines, INITIAL_ITEMS);
943 char **vlines = nil;
944 if (sep != nil) {
945 int l = strlen(sep);
946 vlines = calloc(nlines, sizeof(char*));
947 check_allocation(vlines);
949 for (int i = 0; lines[i] != nil; i++) {
950 char *t = strstr(lines[i], sep);
951 if (t == nil)
952 vlines[i] = lines[i];
953 else
954 vlines[i] = t + l;
958 setlocale(LC_ALL, getenv("LANG"));
960 enum state status = LOOPING;
962 // where the monitor start (used only with xinerama)
963 int offset_x = 0;
964 int offset_y = 0;
966 // width and height of the window
967 int width = 400;
968 int height = 20;
970 // position on the screen
971 int x = 0;
972 int y = 0;
974 // the default padding
975 int padding = 10;
977 // the default borders
978 int border_n = 0;
979 int border_e = 0;
980 int border_s = 0;
981 int border_w = 0;
983 // the prompt. We duplicate the string so later is easy to free (in
984 // the case the user provide its own prompt)
985 char *ps1 = strdup("$ ");
986 check_allocation(ps1);
988 // same for the font name
989 char *fontname = strdup(default_fontname);
990 check_allocation(fontname);
992 int textlen = 10;
993 char *text = malloc(textlen * sizeof(char));
994 check_allocation(text);
996 /* struct completions *cs = filter(text, lines); */
997 struct completions *cs = compls_new();
998 check_allocation(cs);
1000 // start talking to xorg
1001 Display *d = XOpenDisplay(nil);
1002 if (d == nil) {
1003 fprintf(stderr, "Could not open display!\n");
1004 return EX_UNAVAILABLE;
1007 Window parent_window;
1008 bool embed = true;
1009 if (! (parent_window_id && (parent_window = strtol(parent_window_id, nil, 0)))) {
1010 parent_window = DefaultRootWindow(d);
1011 embed = false;
1014 // get display size
1015 int d_width;
1016 int d_height;
1017 get_wh(d, &parent_window, &d_width, &d_height);
1019 #ifdef USE_XINERAMA
1020 if (!embed && XineramaIsActive(d)) {
1021 // find the mice
1022 int number_of_screens = XScreenCount(d);
1023 Window r;
1024 Window root;
1025 int root_x, root_y, win_x, win_y;
1026 unsigned int mask;
1027 bool res;
1028 for (int i = 0; i < number_of_screens; ++i) {
1029 root = XRootWindow(d, i);
1030 res = XQueryPointer(d, root, &r, &r, &root_x, &root_y, &win_x, &win_y, &mask);
1031 if (res) break;
1033 if (!res) {
1034 fprintf(stderr, "No mouse found.\n");
1035 root_x = 0;
1036 root_y = 0;
1039 // now find in which monitor the mice is on
1040 int monitors;
1041 XineramaScreenInfo *info = XineramaQueryScreens(d, &monitors);
1042 if (info) {
1043 for (int i = 0; i < monitors; ++i) {
1044 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
1045 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
1046 offset_x = info[i].x_org;
1047 offset_y = info[i].y_org;
1048 d_width = info[i].width;
1049 d_height = info[i].height;
1050 break;
1054 XFree(info);
1056 #endif
1058 Colormap cmap = DefaultColormap(d, DefaultScreen(d));
1059 XColor p_fg, p_bg,
1060 compl_fg, compl_bg,
1061 compl_highlighted_fg, compl_highlighted_bg,
1062 border_n_bg, border_e_bg, border_s_bg, border_w_bg;
1064 bool horizontal_layout = true;
1066 // read resource
1067 XrmInitialize();
1068 char *xrm = XResourceManagerString(d);
1069 XrmDatabase xdb = nil;
1070 if (xrm != nil) {
1071 xdb = XrmGetStringDatabase(xrm);
1072 XrmValue value;
1073 char *datatype[20];
1075 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
1076 fontname = strdup(value.addr);
1077 check_allocation(fontname);
1078 } else {
1079 fprintf(stderr, "no font defined, using %s\n", fontname);
1082 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == true)
1083 horizontal_layout = !strcmp(value.addr, "horizontal");
1084 else
1085 fprintf(stderr, "no layout defined, using horizontal\n");
1087 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == true) {
1088 free(ps1);
1089 ps1 = normalize_str(value.addr);
1090 } else {
1091 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", ps1);
1094 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
1095 width = parse_int_with_percentage(value.addr, width, d_width);
1096 else
1097 fprintf(stderr, "no width defined, using %d\n", width);
1099 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
1100 height = parse_int_with_percentage(value.addr, height, d_height);
1101 else
1102 fprintf(stderr, "no height defined, using %d\n", height);
1104 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
1105 x = parse_int_with_pos(value.addr, x, d_width, width);
1106 else
1107 fprintf(stderr, "no x defined, using %d\n", x);
1109 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
1110 y = parse_int_with_pos(value.addr, y, d_height, height);
1111 else
1112 fprintf(stderr, "no y defined, using %d\n", y);
1114 if (XrmGetResource(xdb, "MyMenu.padding", "*", datatype, &value) == true)
1115 padding = parse_integer(value.addr, padding);
1116 else
1117 fprintf(stderr, "no padding defined, using %d\n", padding);
1119 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value) == true) {
1120 char **borders = parse_csslike(value.addr);
1121 if (borders != nil) {
1122 border_n = parse_integer(borders[0], 0);
1123 border_e = parse_integer(borders[1], 0);
1124 border_s = parse_integer(borders[2], 0);
1125 border_w = parse_integer(borders[3], 0);
1126 } else {
1127 fprintf(stderr, "error while parsing MyMenu.border.size\n");
1129 } else {
1130 fprintf(stderr, "no border defined, using 0.\n");
1133 XColor tmp;
1134 // TODO: tmp needs to be free'd after every allocation?
1136 // prompt
1137 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
1138 XAllocNamedColor(d, cmap, value.addr, &p_fg, &tmp);
1139 else
1140 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
1142 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
1143 XAllocNamedColor(d, cmap, value.addr, &p_bg, &tmp);
1144 else
1145 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
1147 // completion
1148 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
1149 XAllocNamedColor(d, cmap, value.addr, &compl_fg, &tmp);
1150 else
1151 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
1153 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
1154 XAllocNamedColor(d, cmap, value.addr, &compl_bg, &tmp);
1155 else
1156 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
1158 // completion highlighted
1159 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
1160 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_fg, &tmp);
1161 else
1162 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
1164 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
1165 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_bg, &tmp);
1166 else
1167 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
1169 // border
1170 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value) == true) {
1171 char **colors = parse_csslike(value.addr);
1172 if (colors != nil) {
1173 XAllocNamedColor(d, cmap, colors[0], &border_n_bg, &tmp);
1174 XAllocNamedColor(d, cmap, colors[1], &border_e_bg, &tmp);
1175 XAllocNamedColor(d, cmap, colors[2], &border_s_bg, &tmp);
1176 XAllocNamedColor(d, cmap, colors[3], &border_w_bg, &tmp);
1177 } else {
1178 fprintf(stderr, "error while parsing MyMenu.border.color\n");
1180 } else {
1181 XAllocNamedColor(d, cmap, "white", &border_n_bg, &tmp);
1182 XAllocNamedColor(d, cmap, "white", &border_e_bg, &tmp);
1183 XAllocNamedColor(d, cmap, "white", &border_s_bg, &tmp);
1184 XAllocNamedColor(d, cmap, "white", &border_w_bg, &tmp);
1186 } else {
1187 XColor tmp;
1188 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
1189 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
1190 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
1191 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
1192 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
1193 XAllocNamedColor(d, cmap, "white", &border_n_bg, &tmp);
1194 XAllocNamedColor(d, cmap, "white", &border_e_bg, &tmp);
1195 XAllocNamedColor(d, cmap, "white", &border_s_bg, &tmp);
1196 XAllocNamedColor(d, cmap, "white", &border_w_bg, &tmp);
1199 // second round of args parsing
1200 optind = 0; // reset the option index
1201 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1202 switch (ch) {
1203 case 'a':
1204 first_selected = true;
1205 break;
1206 case 'A':
1207 // free_text -- this case was already catched
1208 break;
1209 case 'd':
1210 // separator -- this case was already catched
1211 break;
1212 case 'e':
1213 // (embedding mymenu) this case was already catched.
1214 break;
1215 case 'p': {
1216 char *newprompt = strdup(optarg);
1217 if (newprompt != nil) {
1218 free(ps1);
1219 ps1 = newprompt;
1221 break;
1223 case 'x':
1224 x = parse_int_with_pos(optarg, x, d_width, width);
1225 break;
1226 case 'y':
1227 y = parse_int_with_pos(optarg, y, d_height, height);
1228 break;
1229 case 'P':
1230 padding = parse_integer(optarg, padding);
1231 break;
1232 case 'l':
1233 horizontal_layout = !strcmp(optarg, "horizontal");
1234 break;
1235 case 'f': {
1236 char *newfont = strdup(optarg);
1237 if (newfont != nil) {
1238 free(fontname);
1239 fontname = newfont;
1241 break;
1243 case 'W':
1244 width = parse_int_with_percentage(optarg, width, d_width);
1245 break;
1246 case 'H':
1247 height = parse_int_with_percentage(optarg, height, d_height);
1248 break;
1249 case 'b': {
1250 char **borders = parse_csslike(optarg);
1251 if (borders != nil) {
1252 border_n = parse_integer(borders[0], 0);
1253 border_e = parse_integer(borders[1], 0);
1254 border_s = parse_integer(borders[2], 0);
1255 border_w = parse_integer(borders[3], 0);
1256 } else {
1257 fprintf(stderr, "Error parsing b option\n");
1259 break;
1261 case 'B': {
1262 char **colors = parse_csslike(optarg);
1263 if (colors != nil) {
1264 XColor tmp;
1265 XAllocNamedColor(d, cmap, colors[0], &border_n_bg, &tmp);
1266 XAllocNamedColor(d, cmap, colors[1], &border_e_bg, &tmp);
1267 XAllocNamedColor(d, cmap, colors[2], &border_s_bg, &tmp);
1268 XAllocNamedColor(d, cmap, colors[3], &border_w_bg, &tmp);
1269 } else {
1270 fprintf(stderr, "error while parsing B option\n");
1272 break;
1274 case 't': {
1275 XColor tmp;
1276 XAllocNamedColor(d, cmap, optarg, &p_fg, &tmp);
1277 break;
1279 case 'T': {
1280 XColor tmp;
1281 XAllocNamedColor(d, cmap, optarg, &p_bg, &tmp);
1282 break;
1284 case 'c': {
1285 XColor tmp;
1286 XAllocNamedColor(d, cmap, optarg, &compl_fg, &tmp);
1287 break;
1289 case 'C': {
1290 XColor tmp;
1291 XAllocNamedColor(d, cmap, optarg, &compl_bg, &tmp);
1292 break;
1294 case 's': {
1295 XColor tmp;
1296 XAllocNamedColor(d, cmap, optarg, &compl_highlighted_fg, &tmp);
1297 break;
1299 case 'S': {
1300 XColor tmp;
1301 XAllocNamedColor(d, cmap, optarg, &compl_highlighted_bg, &tmp);
1302 break;
1304 default:
1305 fprintf(stderr, "Unrecognized option %c\n", ch);
1306 status = ERR;
1307 break;
1311 // since only now we know if the first should be selected, update
1312 // the completion here
1313 update_completions(cs, text, lines, vlines, first_selected);
1315 // load the font
1316 #ifdef USE_XFT
1317 XftFont *font = XftFontOpenName(d, DefaultScreen(d), fontname);
1318 #else
1319 char **missing_charset_list;
1320 int missing_charset_count;
1321 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
1322 if (font == nil) {
1323 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1324 return EX_UNAVAILABLE;
1326 #endif
1328 // create the window
1329 XSetWindowAttributes attr;
1330 attr.override_redirect = true;
1331 attr.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
1333 Window w = XCreateWindow(d, // display
1334 parent_window, // parent
1335 x + offset_x, y + offset_y, // x y
1336 width, height, // w h
1337 0, // border width
1338 CopyFromParent, // depth
1339 InputOutput, // class
1340 CopyFromParent, // visual
1341 CWEventMask | CWOverrideRedirect, // value mask (CWBackPixel in the future also?)
1342 &attr);
1344 set_win_atoms_hints(d, w, width, height);
1346 // we want some events
1347 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeymapStateMask);
1348 XMapRaised(d, w);
1350 // if embed, listen for other events as well
1351 if (embed) {
1352 XSelectInput(d, parent_window, FocusChangeMask);
1353 Window *children, parent, root;
1354 unsigned int children_no;
1355 if (XQueryTree(d, parent_window, &root, &parent, &children, &children_no) && children) {
1356 for (unsigned int i = 0; i < children_no && children[i] != w; ++i)
1357 XSelectInput(d, children[i], FocusChangeMask);
1358 XFree(children);
1360 grabfocus(d, w);
1363 // grab keyboard
1364 take_keyboard(d, w);
1366 // Create some graphics contexts
1367 XGCValues values;
1368 /* values.font = font->fid; */
1370 struct rendering r = {
1371 .d = d,
1372 .w = w,
1373 .width = width,
1374 .height = height,
1375 .padding = padding,
1376 .x_zero = border_w,
1377 .y_zero = border_n,
1378 .border_n = border_n,
1379 .border_e = border_e,
1380 .border_s = border_s,
1381 .border_w = border_w,
1382 .horizontal_layout = horizontal_layout,
1383 .ps1 = ps1,
1384 .ps1len = strlen(ps1),
1385 .prompt = XCreateGC(d, w, 0, &values),
1386 .prompt_bg = XCreateGC(d, w, 0, &values),
1387 .completion = XCreateGC(d, w, 0, &values),
1388 .completion_bg = XCreateGC(d, w, 0, &values),
1389 .completion_highlighted = XCreateGC(d, w, 0, &values),
1390 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
1391 .border_n_bg = XCreateGC(d, w, 0, &values),
1392 .border_e_bg = XCreateGC(d, w, 0, &values),
1393 .border_s_bg = XCreateGC(d, w, 0, &values),
1394 .border_w_bg = XCreateGC(d, w, 0, &values),
1395 #ifdef USE_XFT
1396 .font = font,
1397 #else
1398 .font = &font,
1399 #endif
1402 #ifdef USE_XFT
1403 r.xftdraw = XftDrawCreate(d, w, DefaultVisual(d, 0), DefaultColormap(d, 0));
1405 // prompt
1406 XRenderColor xrcolor;
1407 xrcolor.red = p_fg.red;
1408 xrcolor.green = p_fg.red;
1409 xrcolor.blue = p_fg.red;
1410 xrcolor.alpha = 65535;
1411 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_prompt);
1413 // completion
1414 xrcolor.red = compl_fg.red;
1415 xrcolor.green = compl_fg.green;
1416 xrcolor.blue = compl_fg.blue;
1417 xrcolor.alpha = 65535;
1418 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion);
1420 // completion highlighted
1421 xrcolor.red = compl_highlighted_fg.red;
1422 xrcolor.green = compl_highlighted_fg.green;
1423 xrcolor.blue = compl_highlighted_fg.blue;
1424 xrcolor.alpha = 65535;
1425 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion_highlighted);
1426 #endif
1428 // load the colors in our GCs
1429 XSetForeground(d, r.prompt, p_fg.pixel);
1430 XSetForeground(d, r.prompt_bg, p_bg.pixel);
1431 XSetForeground(d, r.completion, compl_fg.pixel);
1432 XSetForeground(d, r.completion_bg, compl_bg.pixel);
1433 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel);
1434 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg.pixel);
1435 XSetForeground(d, r.border_n_bg, border_n_bg.pixel);
1436 XSetForeground(d, r.border_e_bg, border_e_bg.pixel);
1437 XSetForeground(d, r.border_s_bg, border_s_bg.pixel);
1438 XSetForeground(d, r.border_w_bg, border_w_bg.pixel);
1440 // open the X input method
1441 XIM xim = XOpenIM(d, xdb, resname, resclass);
1442 check_allocation(xim);
1444 XIMStyles *xis = nil;
1445 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1446 fprintf(stderr, "Input Styles could not be retrieved\n");
1447 return EX_UNAVAILABLE;
1450 XIMStyle bestMatchStyle = 0;
1451 for (int i = 0; i < xis->count_styles; ++i) {
1452 XIMStyle ts = xis->supported_styles[i];
1453 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1454 bestMatchStyle = ts;
1455 break;
1458 XFree(xis);
1460 if (!bestMatchStyle) {
1461 fprintf(stderr, "No matching input style could be determined\n");
1464 XIC xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
1465 check_allocation(xic);
1467 // draw the window for the first time
1468 draw(&r, text, cs);
1470 // main loop
1471 while (status == LOOPING) {
1472 XEvent e;
1473 XNextEvent(d, &e);
1475 if (XFilterEvent(&e, w))
1476 continue;
1478 switch (e.type) {
1479 case KeymapNotify:
1480 XRefreshKeyboardMapping(&e.xmapping);
1481 break;
1483 case FocusIn:
1484 // re-grab focus
1485 if (e.xfocus.window != w)
1486 grabfocus(d, w);
1487 break;
1489 case VisibilityNotify:
1490 if (e.xvisibility.state != VisibilityUnobscured)
1491 XRaiseWindow(d, w);
1492 break;
1494 case MapNotify:
1495 /* fprintf(stderr, "Map Notify!\n"); */
1496 /* TODO: update the computed window and height! */
1497 /* get_wh(d, &w, width, height); */
1498 draw(&r, text, cs);
1499 break;
1501 case KeyPress: {
1502 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
1504 char *input;
1505 switch (parse_event(d, ev, xic, &input)) {
1506 case EXIT:
1507 status = ERR;
1508 break;
1510 case CONFIRM: {
1511 status = OK;
1512 if ((cs->selected != -1) || (cs->lenght > 0 && first_selected)) {
1513 // if there is something selected expand it and return
1514 int index = cs->selected == -1 ? 0 : cs->selected;
1515 struct completion *c = cs->completions;
1516 while (true) {
1517 if (index == 0)
1518 break;
1519 c = c->next;
1520 index--;
1522 char *t = c->rcompletion;
1523 free(text);
1524 text = strdup(t);
1525 if (text == nil) {
1526 fprintf(stderr, "Memory allocation error\n");
1527 status = ERR;
1529 textlen = strlen(text);
1530 } else {
1531 if (!free_text) {
1532 // cannot accept arbitrary text
1533 status = LOOPING;
1536 break;
1539 case PREV_COMPL: {
1540 complete(cs, first_selected, true, &text, &textlen, &status);
1541 break;
1544 case NEXT_COMPL: {
1545 complete(cs, first_selected, false, &text, &textlen, &status);
1546 break;
1549 case DEL_CHAR:
1550 popc(text);
1551 update_completions(cs, text, lines, vlines, first_selected);
1552 break;
1554 case DEL_WORD: {
1555 popw(text);
1556 update_completions(cs, text, lines, vlines, first_selected);
1557 break;
1560 case DEL_LINE: {
1561 for (int i = 0; i < textlen; ++i)
1562 text[i] = 0;
1563 update_completions(cs, text, lines, vlines, first_selected);
1564 break;
1567 case ADD_CHAR: {
1568 int str_len = strlen(input);
1570 // sometimes a strange key is pressed (i.e. ctrl alone),
1571 // so input will be empty. Don't need to update completion
1572 // in this case
1573 if (str_len == 0)
1574 break;
1576 for (int i = 0; i < str_len; ++i) {
1577 textlen = pushc(&text, textlen, input[i]);
1578 if (textlen == -1) {
1579 fprintf(stderr, "Memory allocation error\n");
1580 status = ERR;
1581 break;
1584 if (status != ERR) {
1585 update_completions(cs, text, lines, vlines, first_selected);
1586 free(input);
1588 break;
1591 case TOGGLE_FIRST_SELECTED:
1592 first_selected = !first_selected;
1593 if (first_selected && cs->selected < 0)
1594 cs->selected = 0;
1595 if (!first_selected && cs->selected == 0)
1596 cs->selected = -1;
1597 break;
1602 draw(&r, text, cs);
1605 if (status == OK)
1606 printf("%s\n", text);
1608 release_keyboard(r.d);
1610 #ifdef USE_XFT
1611 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_prompt);
1612 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion);
1613 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion_highlighted);
1614 #endif
1616 free(ps1);
1617 free(fontname);
1618 free(text);
1620 char *l = nil;
1621 char **lns = lines;
1622 while ((l = *lns) != nil) {
1623 free(l);
1624 ++lns;
1627 free(lines);
1628 free(vlines);
1629 compls_delete(cs);
1631 XDestroyWindow(r.d, r.w);
1632 XCloseDisplay(r.d);
1634 return status != OK;