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 #define INITIAL_ITEMS 64
57 #define check_allocation(a) { \
58 if (a == nil) { \
59 fprintf(stderr, "Could not allocate memory\n"); \
60 abort(); \
61 } \
62 }
64 #define inner_height(r) (r->height - r->border_n - r->border_s)
65 #define inner_width(r) (r->width - r->border_e - r->border_w)
67 // The possible state of the event loop.
68 enum state {LOOPING, OK, ERR};
70 // for the drawing-related function. The text to be rendered could be
71 // the prompt, a completion or a highlighted completion
72 enum text_type {PROMPT, COMPL, COMPL_HIGH};
74 // These are the possible action to be performed after user input.
75 enum action {
76 EXIT,
77 CONFIRM,
78 NEXT_COMPL,
79 PREV_COMPL,
80 DEL_CHAR,
81 DEL_WORD,
82 DEL_LINE,
83 ADD_CHAR,
84 TOGGLE_FIRST_SELECTED
85 };
87 struct rendering {
88 Display *d; // connection to xorg
89 Window w;
90 int width;
91 int height;
92 int padding;
93 int x_zero; // the "zero" on the x axis (may not be 0 'cause the border)
94 int y_zero; // the same a x_zero, only for the y axis
96 // The four border
97 int border_n;
98 int border_e;
99 int border_s;
100 int border_w;
102 bool horizontal_layout;
104 // the prompt
105 char *ps1;
106 int ps1len;
108 // colors
109 GC prompt;
110 GC prompt_bg;
111 GC completion;
112 GC completion_bg;
113 GC completion_highlighted;
114 GC completion_highlighted_bg;
115 GC border_n_bg;
116 GC border_e_bg;
117 GC border_s_bg;
118 GC border_w_bg;
119 #ifdef USE_XFT
120 XftFont *font;
121 XftDraw *xftdraw;
122 XftColor xft_prompt;
123 XftColor xft_completion;
124 XftColor xft_completion_highlighted;
125 #else
126 XFontSet *font;
127 #endif
128 };
130 // A simple linked list to store the completions.
131 struct completion {
132 char *completion;
133 struct completion *next;
134 };
136 struct completions {
137 struct completion *completions;
138 int selected;
139 int lenght;
140 };
142 // return a newly allocated (and empty) completion list
143 struct completions *compls_new() {
144 struct completions *cs = malloc(sizeof(struct completions));
146 if (cs == nil)
147 return cs;
149 cs->completions = nil;
150 cs->selected = -1;
151 cs->lenght = 0;
152 return cs;
155 struct completion *compl_new() {
156 struct completion *c = malloc(sizeof(struct completion));
157 if (c == nil)
158 return c;
160 c->completion = nil;
161 c->next = nil;
162 return c;
165 // delete ONLY the given completion (i.e. does not free c->next...)
166 void compl_delete(struct completion *c) {
167 free(c);
170 // delete the current completion and the next (c->next) and so on...
171 void compl_delete_rec(struct completion *c) {
172 while (c != nil) {
173 struct completion *t = c->next;
174 free(c);
175 c = t;
179 void compls_delete(struct completions *cs) {
180 if (cs == nil)
181 return;
183 compl_delete_rec(cs->completions);
184 free(cs);
187 // create a completion list from a text and the list of possible
188 // completions (null terminated). Expects a non-null `cs'.
189 void filter(struct completions *cs, char *text, char **lines) {
190 struct completion *c = compl_new();
191 if (c == nil) {
192 return;
195 cs->completions = c;
197 int index = 0;
198 int matching = 0;
200 while (true) {
201 char *l = lines[index];
202 if (l == nil)
203 break;
205 if (strcasestr(l, text) != nil) {
206 matching++;
208 c->next = compl_new();
209 c = c->next;
210 if (c == nil) {
211 compls_delete(cs);
212 return;
214 c->completion = l;
217 index++;
220 struct completion *f = cs->completions->next;
221 compl_delete(cs->completions);
222 cs->completions = f;
223 cs->lenght = matching;
224 cs->selected = -1;
227 // update the given completion, that is: clean the old cs & generate a new one.
228 void update_completions(struct completions *cs, char *text, char **lines, bool first_selected) {
229 compl_delete_rec(cs->completions);
230 filter(cs, text, lines);
231 if (first_selected && cs->lenght > 0)
232 cs->selected = 0;
235 // select the next, or the previous, selection and update some
236 // state. `text' will be updated with the text of the completion and
237 // `textlen' with the new lenght of `text'. If the memory cannot be
238 // allocated, `status' will be set to `ERR'.
239 void complete(struct completions *cs, bool first_selected, bool p, char **text, int *textlen, enum state *status) {
240 if (cs == nil || cs->lenght == 0)
241 return;
243 // if the first is always selected, and the first entry is different
244 // from the text, expand the text and return
245 if (first_selected
246 && cs->selected == 0
247 && strcmp(cs->completions->completion, *text) != 0
248 && !p) {
249 free(*text);
250 *text = strdup(cs->completions->completion);
251 if (text == nil) {
252 *status = ERR;
253 return;
255 *textlen = strlen(*text);
256 return;
259 int index = cs->selected;
261 if (index == -1 && p)
262 index = 0;
263 index = cs->selected = (cs->lenght + (p ? index - 1 : index + 1)) % cs->lenght;
265 struct completion *n = cs->completions;
267 // find the selected item
268 while (index != 0) {
269 index--;
270 n = n->next;
273 free(*text);
274 *text = strdup(n->completion);
275 if (text == nil) {
276 fprintf(stderr, "Memory allocation error!\n");
277 *status = ERR;
278 return;
280 *textlen = strlen(*text);
283 // push the character c at the end of the string pointed by p
284 int pushc(char **p, int maxlen, char c) {
285 int len = strnlen(*p, maxlen);
287 if (!(len < maxlen -2)) {
288 maxlen += maxlen >> 1;
289 char *newptr = realloc(*p, maxlen);
290 if (newptr == nil) { // bad!
291 return -1;
293 *p = newptr;
296 (*p)[len] = c;
297 (*p)[len+1] = '\0';
298 return maxlen;
301 // return the number of character
302 int utf8strnlen(char *s, int maxlen) {
303 int len = 0;
304 while (*s && maxlen > 0) {
305 len += (*s++ & 0xc0) != 0x80;
306 maxlen--;
308 return len;
311 // remove the last *glyph* from the *utf8* string!
312 // this is different from just setting the last byte to 0 (in some
313 // cases ofc). The actual implementation is quite inefficient because
314 // it remove the last byte until the number of glyphs doesn't change
315 void popc(char *p, int maxlen) {
316 int len = strnlen(p, maxlen);
318 if (len == 0)
319 return;
321 int ulen = utf8strnlen(p, maxlen);
322 while (len > 0 && utf8strnlen(p, maxlen) == ulen) {
323 len--;
324 p[len] = 0;
328 // If the string is surrounded by quotes (`"`) remove them and replace
329 // every `\"` in the string with `"`
330 char *normalize_str(const char *str) {
331 int len = strlen(str);
332 if (len == 0)
333 return nil;
335 char *s = calloc(len, sizeof(char));
336 check_allocation(s);
337 int p = 0;
338 while (*str) {
339 char c = *str;
340 if (*str == '\\') {
341 if (*(str + 1)) {
342 s[p] = *(str + 1);
343 p++;
344 str += 2; // skip this and the next char
345 continue;
346 } else {
347 break;
350 if (c == '"') {
351 str++; // skip only this char
352 continue;
354 s[p] = c;
355 p++;
356 str++;
358 return s;
361 // read an arbitrary long line from stdin and return a pointer to it
362 // TODO: resize the allocated memory to exactly fit the string once
363 // read?
364 char *readline(bool *eof) {
365 int maxlen = 8;
366 char *str = calloc(maxlen, sizeof(char));
367 if (str == nil) {
368 fprintf(stderr, "Cannot allocate memory!\n");
369 exit(EX_UNAVAILABLE);
372 int c;
373 while((c = getchar()) != EOF) {
374 if (c == '\n')
375 return str;
376 else
377 maxlen = pushc(&str, maxlen, c);
379 if (maxlen == -1) {
380 fprintf(stderr, "Cannot allocate memory!\n");
381 exit(EX_UNAVAILABLE);
384 *eof = true;
385 return str;
388 // read an arbitrary amount of text until an EOF and store it in
389 // lns. `items` is the capacity of lns. It may increase lns with
390 // `realloc(3)` to store more line. Return the number of lines
391 // read. The last item will always be a NULL pointer. It ignore the
392 // "null" (empty) lines
393 int readlines (char ***lns, int items) {
394 bool finished = false;
395 int n = 0;
396 char **lines = *lns;
397 while (true) {
398 lines[n] = readline(&finished);
400 if (strlen(lines[n]) == 0 || lines[n][0] == '\n') {
401 free(lines[n]);
402 --n; // forget about this line
405 if (finished)
406 break;
408 ++n;
410 if (n == items - 1) {
411 items += items >>1;
412 char **l = realloc(lines, sizeof(char*) * items);
413 check_allocation(l);
414 *lns = l;
415 lines = l;
419 n++;
420 lines[n] = nil;
421 return items;
424 // Compute the dimension of the string str once rendered, return the
425 // width and save the width and the height in ret_width and ret_height
426 int text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height) {
427 int height;
428 int width;
429 #ifdef USE_XFT
430 XGlyphInfo gi;
431 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
432 /* height = gi.height; */
433 /* height = (gi.height + (r->font->ascent - r->font->descent)/2) / 2; */
434 /* height = (r->font->ascent - r->font->descent)/2 + gi.height*2; */
435 height = r->font->ascent - r->font->descent;
436 width = gi.width - gi.x;
437 #else
438 XRectangle rect;
439 XmbTextExtents(*r->font, str, len, nil, &rect);
440 height = rect.height;
441 width = rect.width;
442 #endif
443 if (ret_width != nil) *ret_width = width;
444 if (ret_height != nil) *ret_height = height;
445 return width;
448 // Draw the string str
449 void draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt) {
450 #ifdef USE_XFT
451 XftColor xftcolor;
452 if (tt == PROMPT) xftcolor = r->xft_prompt;
453 if (tt == COMPL) xftcolor = r->xft_completion;
454 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
456 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
457 #else
458 GC gc;
459 if (tt == PROMPT) gc = r->prompt;
460 if (tt == COMPL) gc = r->completion;
461 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
462 Xutf8DrawString(r->d, r->w, *r->font, gc, x, y, str, len);
463 #endif
466 // Duplicate the string str and substitute every space with a 'n'
467 char *strdupn(char *str) {
468 int len = strlen(str);
470 if (str == nil || len == 0)
471 return nil;
473 char *dup = strdup(str);
474 if (dup == nil)
475 return nil;
477 for (int i = 0; i < len; ++i)
478 if (dup[i] == ' ')
479 dup[i] = 'n';
481 return dup;
484 // |------------------|----------------------------------------------|
485 // | 20 char text | completion | completion | completion | compl |
486 // |------------------|----------------------------------------------|
487 void draw_horizontally(struct rendering *r, char *text, struct completions *cs) {
488 int prompt_width = 20; // char
490 int width, height;
491 int ps1xlen = text_extents(r->ps1, r->ps1len, r, &width, &height);
492 int start_at = ps1xlen;
494 start_at = r->x_zero + text_extents("n", 1, r, nil, nil);
495 start_at = start_at * prompt_width + r->padding;
497 int texty = (inner_height(r) + height + r->y_zero) / 2;
499 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, start_at, inner_height(r));
501 int text_len = strlen(text);
502 if (text_len > prompt_width)
503 text = text + (text_len - prompt_width);
504 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, texty, r, PROMPT);
505 draw_string(text, MIN(text_len, prompt_width), r->x_zero + r->padding + ps1xlen, texty, r, PROMPT);
507 XFillRectangle(r->d, r->w, r->completion_bg, start_at, r->y_zero, r->width, inner_height(r));
509 struct completion *c = cs->completions;
510 for (int i = 0; c != nil; ++i) {
511 enum text_type tt = cs->selected == i ? COMPL_HIGH : COMPL;
512 GC h = cs->selected == i ? r->completion_highlighted_bg : r->completion_bg;
514 int len = strlen(c->completion);
515 int text_width = text_extents(c->completion, len, r, nil, nil);
517 XFillRectangle(r->d, r->w, h, start_at, r->y_zero, text_width + r->padding*2, inner_height(r));
519 draw_string(c->completion, len, start_at + r->padding, texty, r, tt);
521 start_at += text_width + r->padding * 2;
523 if (start_at > inner_width(r))
524 break; // don't draw completion if the space isn't enough
526 c = c->next;
530 // |-----------------------------------------------------------------|
531 // | prompt |
532 // |-----------------------------------------------------------------|
533 // | completion |
534 // |-----------------------------------------------------------------|
535 // | completion |
536 // |-----------------------------------------------------------------|
537 void draw_vertically(struct rendering *r, char *text, struct completions *cs) {
538 int height, width;
539 text_extents("fjpgl", 5, r, nil, &height);
540 int start_at = height + r->padding;
542 XFillRectangle(r->d, r->w, r->completion_bg, r->x_zero, r->y_zero, r->width, r->height);
543 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, r->width, start_at);
545 int ps1xlen = text_extents(r->ps1, r->ps1len, r, nil, nil);
547 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, r->y_zero + height + r->padding, r, PROMPT);
548 draw_string(text, strlen(text), r->x_zero + r->padding + ps1xlen, r->y_zero + height + r->padding, r, PROMPT);
550 start_at += r->padding + r->y_zero;
552 struct completion *c = cs->completions;
553 for (int i = 0; c != nil; ++i){
554 enum text_type tt = cs->selected == i ? COMPL_HIGH : COMPL;
555 GC h = cs->selected == i ? r->completion_highlighted_bg : r->completion_bg;
557 int len = strlen(c->completion);
558 text_extents(c->completion, len, r, &width, &height);
559 XFillRectangle(r->d, r->w, h, r->x_zero, start_at, inner_width(r), height + r->padding*2);
560 draw_string(c->completion, len, r->x_zero + r->padding, start_at + height + r->padding, r, tt);
562 start_at += height + r->padding *2;
564 if (start_at > inner_height(r))
565 break; // don't draw completion if the space isn't enough
567 c = c->next;
571 void draw(struct rendering *r, char *text, struct completions *cs) {
572 if (r->horizontal_layout)
573 draw_horizontally(r, text, cs);
574 else
575 draw_vertically(r, text, cs);
577 // draw the borders
579 if (r->border_w != 0)
580 XFillRectangle(r->d, r->w, r->border_w_bg, 0, 0, r->border_w, r->height);
582 if (r->border_e != 0)
583 XFillRectangle(r->d, r->w, r->border_e_bg, r->width - r->border_e, 0, r->border_e, r->height);
585 if (r->border_n != 0)
586 XFillRectangle(r->d, r->w, r->border_n_bg, 0, 0, r->width, r->border_n);
588 if (r->border_s != 0)
589 XFillRectangle(r->d, r->w, r->border_s_bg, 0, r->height - r->border_s, r->width, r->border_s);
591 // send all the work to x
592 XFlush(r->d);
595 /* Set some WM stuff */
596 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
597 Atom type;
598 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
599 XChangeProperty(
600 d,
601 w,
602 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
603 XInternAtom(d, "ATOM", false),
604 32,
605 PropModeReplace,
606 (unsigned char *)&type,
608 );
610 /* some window managers honor this properties */
611 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
612 XChangeProperty(d,
613 w,
614 XInternAtom(d, "_NET_WM_STATE", false),
615 XInternAtom(d, "ATOM", false),
616 32,
617 PropModeReplace,
618 (unsigned char *)&type,
620 );
622 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
623 XChangeProperty(d,
624 w,
625 XInternAtom(d, "_NET_WM_STATE", false),
626 XInternAtom(d, "ATOM", false),
627 32,
628 PropModeAppend,
629 (unsigned char *)&type,
631 );
633 // setting window hints
634 XClassHint *class_hint = XAllocClassHint();
635 if (class_hint == nil) {
636 fprintf(stderr, "Could not allocate memory for class hint\n");
637 exit(EX_UNAVAILABLE);
639 class_hint->res_name = resname;
640 class_hint->res_class = resclass;
641 XSetClassHint(d, w, class_hint);
642 XFree(class_hint);
644 XSizeHints *size_hint = XAllocSizeHints();
645 if (size_hint == nil) {
646 fprintf(stderr, "Could not allocate memory for size hint\n");
647 exit(EX_UNAVAILABLE);
649 size_hint->flags = PMinSize | PBaseSize;
650 size_hint->min_width = width;
651 size_hint->base_width = width;
652 size_hint->min_height = height;
653 size_hint->base_height = height;
655 XFlush(d);
658 // write the width and height of the window `w' respectively in `width'
659 // and `height'.
660 void get_wh(Display *d, Window *w, int *width, int *height) {
661 XWindowAttributes win_attr;
662 XGetWindowAttributes(d, *w, &win_attr);
663 *height = win_attr.height;
664 *width = win_attr.width;
667 int grabfocus(Display *d, Window w) {
668 for (int i = 0; i < 100; ++i) {
669 Window focuswin;
670 int revert_to_win;
671 XGetInputFocus(d, &focuswin, &revert_to_win);
672 if (focuswin == w)
673 return true;
674 XSetInputFocus(d, w, RevertToParent, CurrentTime);
675 usleep(1000);
677 return 0;
680 // I know this may seem a little hackish BUT is the only way I managed
681 // to actually grab that goddam keyboard. Only one call to
682 // XGrabKeyboard does not always end up with the keyboard grabbed!
683 int take_keyboard(Display *d, Window w) {
684 int i;
685 for (i = 0; i < 100; i++) {
686 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
687 return 1;
688 usleep(1000);
690 fprintf(stderr, "Cannot grab keyboard\n");
691 return 0;
694 // release the keyboard.
695 void release_keyboard(Display *d) {
696 XUngrabKeyboard(d, CurrentTime);
699 // Given a string, try to parse it as a number or return
700 // `default_value'.
701 int parse_integer(const char *str, int default_value) {
702 errno = 0;
703 char *ep;
704 long lval = strtol(str, &ep, 10);
705 if (str[0] == '\0' || *ep != '\0') { // NaN
706 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
707 return default_value;
709 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
710 (lval > INT_MAX || lval < INT_MIN)) {
711 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
712 return default_value;
714 return lval;
717 // like parse_integer, but if the value ends with a `%' then its
718 // treated like a percentage (`max' is used to compute the percentage)
719 int parse_int_with_percentage(const char *str, int default_value, int max) {
720 int len = strlen(str);
721 if (len > 0 && str[len-1] == '%') {
722 char *cpy = strdup(str);
723 check_allocation(cpy);
724 cpy[len-1] = '\0';
725 int val = parse_integer(cpy, default_value);
726 free(cpy);
727 return val * max / 100;
729 return parse_integer(str, default_value);
732 // like parse_int_with_percentage but understands some special values
733 // - "middle" that is (max - self) / 2
734 // - "start" that is 0
735 // - "end" that is (max - self)
736 int parse_int_with_pos(const char *str, int default_value, int max, int self) {
737 if (!strcmp(str, "start"))
738 return 0;
739 if (!strcmp(str, "middle"))
740 return (max - self)/2;
741 if (!strcmp(str, "end"))
742 return max-self;
743 return parse_int_with_percentage(str, default_value, max);
746 // parse a string like a css value (for example like the css
747 // margin/padding properties). Will ALWAYS return an array of 4 word
748 // TODO: harden this function!
749 char **parse_csslike(const char *str) {
750 char *s = strdup(str);
751 if (s == nil)
752 return nil;
754 char **ret = malloc(4 * sizeof(char*));
755 if (ret == nil) {
756 free(s);
757 return nil;
760 int i = 0;
761 char *token;
762 while ((token = strsep(&s, " ")) != NULL && i < 4) {
763 ret[i] = strdup(token);
764 i++;
767 if (i == 1)
768 for (int j = 1; j < 4; j++)
769 ret[j] = strdup(ret[0]);
771 if (i == 2) {
772 ret[2] = strdup(ret[0]);
773 ret[3] = strdup(ret[1]);
776 if (i == 3)
777 ret[3] = strdup(ret[1]);
779 // Before we didn't check for the return type of strdup, here we will
781 bool any_null = false;
782 for (int i = 0; i < 4; ++i)
783 any_null = ret[i] == nil || any_null;
785 if (any_null)
786 for (int i = 0; i < 4; ++i)
787 if (ret[i] != nil)
788 free(ret[i]);
790 if (i == 0 || any_null) {
791 free(s);
792 free(ret);
793 return nil;
796 return ret;
799 // Given an event, try to understand what the user wants. If the
800 // return value is ADD_CHAR then `input' is a pointer to a string that
801 // will need to be free'ed.
802 enum action parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input) {
803 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
804 return DEL_CHAR;
806 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
807 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
809 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
810 return CONFIRM;
812 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
813 return EXIT;
815 // try to read what the user pressed
816 char str[SYM_BUF_SIZE] = {0};
817 Status s = 0;
818 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
819 if (s == XBufferOverflow) {
820 // should not happen since there are no utf-8 characters larger
821 // than 24bits
822 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
823 return EXIT;
826 if (ev->state & ControlMask) {
827 if (!strcmp(str, "")) // C-u
828 return DEL_LINE;
829 if (!strcmp(str, "")) // C-w
830 return DEL_WORD;
831 if (!strcmp(str, "")) // C-h
832 return DEL_CHAR;
833 if (!strcmp(str, "\r")) // C-m
834 return CONFIRM;
835 if (!strcmp(str, "")) // C-p
836 return PREV_COMPL;
837 if (!strcmp(str, "")) // C-n
838 return NEXT_COMPL;
839 if (!strcmp(str, "")) // C-c
840 return EXIT;
841 if (!strcmp(str, "\t")) // C-i
842 return TOGGLE_FIRST_SELECTED;
845 *input = strdup(str);
846 if (*input == nil) {
847 fprintf(stderr, "Error while allocating memory for key.\n");
848 return EXIT;
851 return ADD_CHAR;
854 // Given the name of the program (argv[0]?) print a small help on stderr
855 void usage(char *prgname) {
856 fprintf(stderr, "%s [-hva] [-p prompt] [-x coord] [-y coord] [-W width] [-H height]\n"
857 " [-P padding] [-l layout] [-f font] [-b borders] [-B colors]\n"
858 " [-t color] [-T color] [-c color] [-C color] [-s color] [-S color]\n"
859 " [-w window_id]\n", prgname);
862 int main(int argc, char **argv) {
863 #ifdef HAVE_PLEDGE
864 // stdio & rpat: to read and write stdio/stdout
865 // unix: to connect to Xorg
866 pledge("stdio rpath unix", "");
867 #endif
869 // by default the first completion isn't selected
870 bool first_selected = false;
872 char *parent_window_id = nil;
874 // first round of args parsing
875 int ch;
876 while ((ch = getopt(argc, argv, ARGS)) != -1) {
877 switch (ch) {
878 case 'h': // help
879 usage(*argv);
880 return 0;
881 case 'v': // version
882 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
883 return 0;
884 case 'e': // embed
885 parent_window_id = strdup(optarg);
886 check_allocation(parent_window_id);
887 break;
888 default:
889 break;
893 char **lines = calloc(INITIAL_ITEMS, sizeof(char*));
894 readlines(&lines, INITIAL_ITEMS);
896 setlocale(LC_ALL, getenv("LANG"));
898 enum state status = LOOPING;
900 // where the monitor start (used only with xinerama)
901 int offset_x = 0;
902 int offset_y = 0;
904 // width and height of the window
905 int width = 400;
906 int height = 20;
908 // position on the screen
909 int x = 0;
910 int y = 0;
912 // the default padding
913 int padding = 10;
915 // the default borders
916 int border_n = 0;
917 int border_e = 0;
918 int border_s = 0;
919 int border_w = 0;
921 // the prompt. We duplicate the string so later is easy to free (in
922 // the case the user provide its own prompt)
923 char *ps1 = strdup("$ ");
924 check_allocation(ps1);
926 // same for the font name
927 char *fontname = strdup(default_fontname);
928 check_allocation(fontname);
930 int textlen = 10;
931 char *text = malloc(textlen * sizeof(char));
932 check_allocation(text);
934 /* struct completions *cs = filter(text, lines); */
935 struct completions *cs = compls_new();
936 check_allocation(cs);
938 // start talking to xorg
939 Display *d = XOpenDisplay(nil);
940 if (d == nil) {
941 fprintf(stderr, "Could not open display!\n");
942 return EX_UNAVAILABLE;
945 Window parent_window;
946 bool embed = true;
947 if (! (parent_window_id && (parent_window = strtol(parent_window_id, nil, 0)))) {
948 parent_window = DefaultRootWindow(d);
949 embed = false;
952 // get display size
953 int d_width;
954 int d_height;
955 get_wh(d, &parent_window, &d_width, &d_height);
957 fprintf(stderr, "d_width %d, d_height %d\n", d_width, d_height);
959 #ifdef USE_XINERAMA
960 if (!embed && XineramaIsActive(d)) {
961 // find the mice
962 int number_of_screens = XScreenCount(d);
963 Window r;
964 Window root;
965 int root_x, root_y, win_x, win_y;
966 unsigned int mask;
967 bool res;
968 for (int i = 0; i < number_of_screens; ++i) {
969 root = XRootWindow(d, i);
970 res = XQueryPointer(d, root, &r, &r, &root_x, &root_y, &win_x, &win_y, &mask);
971 if (res) break;
973 if (!res) {
974 fprintf(stderr, "No mouse found.\n");
975 root_x = 0;
976 root_y = 0;
979 // now find in which monitor the mice is on
980 int monitors;
981 XineramaScreenInfo *info = XineramaQueryScreens(d, &monitors);
982 if (info) {
983 for (int i = 0; i < monitors; ++i) {
984 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
985 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
986 offset_x = info[i].x_org;
987 offset_y = info[i].y_org;
988 d_width = info[i].width;
989 d_height = info[i].height;
990 break;
994 XFree(info);
996 #endif
998 Colormap cmap = DefaultColormap(d, DefaultScreen(d));
999 XColor p_fg, p_bg,
1000 compl_fg, compl_bg,
1001 compl_highlighted_fg, compl_highlighted_bg,
1002 border_n_bg, border_e_bg, border_s_bg, border_w_bg;
1004 bool horizontal_layout = true;
1006 // read resource
1007 XrmInitialize();
1008 char *xrm = XResourceManagerString(d);
1009 XrmDatabase xdb = nil;
1010 if (xrm != nil) {
1011 xdb = XrmGetStringDatabase(xrm);
1012 XrmValue value;
1013 char *datatype[20];
1015 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
1016 fontname = strdup(value.addr);
1017 check_allocation(fontname);
1019 else
1020 fprintf(stderr, "no font defined, using %s\n", fontname);
1022 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == true) {
1023 horizontal_layout = !strcmp(value.addr, "horizontal");
1025 else
1026 fprintf(stderr, "no layout defined, using horizontal\n");
1028 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == true) {
1029 free(ps1);
1030 ps1 = normalize_str(value.addr);
1031 } else
1032 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", ps1);
1034 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
1035 width = parse_int_with_percentage(value.addr, width, d_width);
1036 else
1037 fprintf(stderr, "no width defined, using %d\n", width);
1039 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
1040 height = parse_int_with_percentage(value.addr, height, d_height);
1041 else
1042 fprintf(stderr, "no height defined, using %d\n", height);
1044 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
1045 x = parse_int_with_pos(value.addr, x, d_width, width);
1046 else
1047 fprintf(stderr, "no x defined, using %d\n", x);
1049 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
1050 y = parse_int_with_pos(value.addr, y, d_height, height);
1051 else
1052 fprintf(stderr, "no y defined, using %d\n", y);
1054 if (XrmGetResource(xdb, "MyMenu.padding", "*", datatype, &value) == true)
1055 padding = parse_integer(value.addr, padding);
1056 else
1057 fprintf(stderr, "no padding defined, using %d\n", padding);
1059 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value) == true) {
1060 char **borders = parse_csslike(value.addr);
1061 if (borders != nil) {
1062 border_n = parse_integer(borders[0], 0);
1063 border_e = parse_integer(borders[1], 0);
1064 border_s = parse_integer(borders[2], 0);
1065 border_w = parse_integer(borders[3], 0);
1066 } else {
1067 fprintf(stderr, "error while parsing MyMenu.border.size\n");
1069 } else {
1070 fprintf(stderr, "no border defined, using 0.\n");
1073 XColor tmp;
1074 // TODO: tmp needs to be free'd after every allocation?
1076 // prompt
1077 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
1078 XAllocNamedColor(d, cmap, value.addr, &p_fg, &tmp);
1079 else
1080 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
1082 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
1083 XAllocNamedColor(d, cmap, value.addr, &p_bg, &tmp);
1084 else
1085 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
1087 // completion
1088 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
1089 XAllocNamedColor(d, cmap, value.addr, &compl_fg, &tmp);
1090 else
1091 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
1093 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
1094 XAllocNamedColor(d, cmap, value.addr, &compl_bg, &tmp);
1095 else
1096 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
1098 // completion highlighted
1099 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
1100 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_fg, &tmp);
1101 else
1102 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
1104 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
1105 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_bg, &tmp);
1106 else
1107 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
1109 // border
1110 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value) == true) {
1111 char **colors = parse_csslike(value.addr);
1112 if (colors != nil) {
1113 XAllocNamedColor(d, cmap, colors[0], &border_n_bg, &tmp);
1114 XAllocNamedColor(d, cmap, colors[1], &border_e_bg, &tmp);
1115 XAllocNamedColor(d, cmap, colors[2], &border_s_bg, &tmp);
1116 XAllocNamedColor(d, cmap, colors[3], &border_w_bg, &tmp);
1117 } else {
1118 fprintf(stderr, "error while parsing MyMenu.border.color\n");
1120 } else {
1121 XAllocNamedColor(d, cmap, "white", &border_n_bg, &tmp);
1122 XAllocNamedColor(d, cmap, "white", &border_e_bg, &tmp);
1123 XAllocNamedColor(d, cmap, "white", &border_s_bg, &tmp);
1124 XAllocNamedColor(d, cmap, "white", &border_w_bg, &tmp);
1126 } else {
1127 XColor tmp;
1128 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
1129 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
1130 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
1131 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
1132 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
1133 XAllocNamedColor(d, cmap, "white", &border_n_bg, &tmp);
1134 XAllocNamedColor(d, cmap, "white", &border_e_bg, &tmp);
1135 XAllocNamedColor(d, cmap, "white", &border_s_bg, &tmp);
1136 XAllocNamedColor(d, cmap, "white", &border_w_bg, &tmp);
1139 // second round of args parsing
1140 optind = 0; // reset the option index
1141 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1142 switch (ch) {
1143 case 'a':
1144 first_selected = true;
1145 break;
1146 case 'e':
1147 // (embedding mymenu) this case was already catched.
1148 break;
1149 case 'p': {
1150 char *newprompt = strdup(optarg);
1151 if (newprompt != nil) {
1152 free(ps1);
1153 ps1 = newprompt;
1155 break;
1157 case 'x':
1158 x = parse_int_with_pos(optarg, x, d_width, width);
1159 break;
1160 case 'y':
1161 y = parse_int_with_pos(optarg, y, d_height, height);
1162 break;
1163 case 'P':
1164 padding = parse_integer(optarg, padding);
1165 break;
1166 case 'l':
1167 horizontal_layout = !strcmp(optarg, "horizontal");
1168 break;
1169 case 'f': {
1170 char *newfont = strdup(optarg);
1171 if (newfont != nil) {
1172 free(fontname);
1173 fontname = newfont;
1175 break;
1177 case 'W':
1178 width = parse_int_with_percentage(optarg, width, d_width);
1179 break;
1180 case 'H':
1181 height = parse_int_with_percentage(optarg, height, d_height);
1182 break;
1183 case 'b': {
1184 char **borders = parse_csslike(optarg);
1185 if (borders != nil) {
1186 border_n = parse_integer(borders[0], 0);
1187 border_e = parse_integer(borders[1], 0);
1188 border_s = parse_integer(borders[2], 0);
1189 border_w = parse_integer(borders[3], 0);
1190 } else {
1191 fprintf(stderr, "Error parsing b option\n");
1193 break;
1195 case 'B': {
1196 char **colors = parse_csslike(optarg);
1197 if (colors != nil) {
1198 XColor tmp;
1199 XAllocNamedColor(d, cmap, colors[0], &border_n_bg, &tmp);
1200 XAllocNamedColor(d, cmap, colors[1], &border_e_bg, &tmp);
1201 XAllocNamedColor(d, cmap, colors[2], &border_s_bg, &tmp);
1202 XAllocNamedColor(d, cmap, colors[3], &border_w_bg, &tmp);
1203 } else {
1204 fprintf(stderr, "error while parsing B option\n");
1206 break;
1208 case 't': {
1209 XColor tmp;
1210 XAllocNamedColor(d, cmap, optarg, &p_fg, &tmp);
1211 break;
1213 case 'T': {
1214 XColor tmp;
1215 XAllocNamedColor(d, cmap, optarg, &p_bg, &tmp);
1216 break;
1218 case 'c': {
1219 XColor tmp;
1220 XAllocNamedColor(d, cmap, optarg, &compl_fg, &tmp);
1221 break;
1223 case 'C': {
1224 XColor tmp;
1225 XAllocNamedColor(d, cmap, optarg, &compl_bg, &tmp);
1226 break;
1228 case 's': {
1229 XColor tmp;
1230 XAllocNamedColor(d, cmap, optarg, &compl_highlighted_fg, &tmp);
1231 break;
1233 case 'S': {
1234 XColor tmp;
1235 XAllocNamedColor(d, cmap, optarg, &compl_highlighted_bg, &tmp);
1236 break;
1238 default:
1239 fprintf(stderr, "Unrecognized option %c\n", ch);
1240 status = ERR;
1241 break;
1245 // since only now we know if the first should be selected, update
1246 // the completion here
1247 update_completions(cs, text, lines, first_selected);
1249 // load the font
1250 #ifdef USE_XFT
1251 XftFont *font = XftFontOpenName(d, DefaultScreen(d), fontname);
1252 #else
1253 char **missing_charset_list;
1254 int missing_charset_count;
1255 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
1256 if (font == nil) {
1257 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1258 return EX_UNAVAILABLE;
1260 #endif
1262 // create the window
1263 XSetWindowAttributes attr;
1264 attr.override_redirect = true;
1265 attr.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
1267 Window w = XCreateWindow(d, // display
1268 parent_window, // parent
1269 x + offset_x, y + offset_y, // x y
1270 width, height, // w h
1271 0, // border width
1272 CopyFromParent, // depth
1273 InputOutput, // class
1274 CopyFromParent, // visual
1275 CWEventMask | CWOverrideRedirect, // value mask (CWBackPixel in the future also?)
1276 &attr);
1278 set_win_atoms_hints(d, w, width, height);
1280 // we want some events
1281 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeymapStateMask);
1282 XMapRaised(d, w);
1284 // if embed, listen for other events as well
1285 if (embed) {
1286 XSelectInput(d, parent_window, FocusChangeMask);
1287 Window *children, parent, root;
1288 unsigned int children_no;
1289 if (XQueryTree(d, parent_window, &root, &parent, &children, &children_no) && children) {
1290 for (unsigned int i = 0; i < children_no && children[i] != w; ++i)
1291 XSelectInput(d, children[i], FocusChangeMask);
1292 XFree(children);
1294 grabfocus(d, w);
1297 // grab keyboard
1298 take_keyboard(d, w);
1300 // Create some graphics contexts
1301 XGCValues values;
1302 /* values.font = font->fid; */
1304 struct rendering r = {
1305 .d = d,
1306 .w = w,
1307 .width = width,
1308 .height = height,
1309 .padding = padding,
1310 .x_zero = border_w,
1311 .y_zero = border_n,
1312 .border_n = border_n,
1313 .border_e = border_e,
1314 .border_s = border_s,
1315 .border_w = border_w,
1316 .horizontal_layout = horizontal_layout,
1317 .ps1 = ps1,
1318 .ps1len = strlen(ps1),
1319 .prompt = XCreateGC(d, w, 0, &values),
1320 .prompt_bg = XCreateGC(d, w, 0, &values),
1321 .completion = XCreateGC(d, w, 0, &values),
1322 .completion_bg = XCreateGC(d, w, 0, &values),
1323 .completion_highlighted = XCreateGC(d, w, 0, &values),
1324 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
1325 .border_n_bg = XCreateGC(d, w, 0, &values),
1326 .border_e_bg = XCreateGC(d, w, 0, &values),
1327 .border_s_bg = XCreateGC(d, w, 0, &values),
1328 .border_w_bg = XCreateGC(d, w, 0, &values),
1329 #ifdef USE_XFT
1330 .font = font,
1331 #else
1332 .font = &font,
1333 #endif
1336 #ifdef USE_XFT
1337 r.xftdraw = XftDrawCreate(d, w, DefaultVisual(d, 0), DefaultColormap(d, 0));
1339 // prompt
1340 XRenderColor xrcolor;
1341 xrcolor.red = p_fg.red;
1342 xrcolor.green = p_fg.red;
1343 xrcolor.blue = p_fg.red;
1344 xrcolor.alpha = 65535;
1345 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_prompt);
1347 // completion
1348 xrcolor.red = compl_fg.red;
1349 xrcolor.green = compl_fg.green;
1350 xrcolor.blue = compl_fg.blue;
1351 xrcolor.alpha = 65535;
1352 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion);
1354 // completion highlighted
1355 xrcolor.red = compl_highlighted_fg.red;
1356 xrcolor.green = compl_highlighted_fg.green;
1357 xrcolor.blue = compl_highlighted_fg.blue;
1358 xrcolor.alpha = 65535;
1359 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion_highlighted);
1360 #endif
1362 // load the colors in our GCs
1363 XSetForeground(d, r.prompt, p_fg.pixel);
1364 XSetForeground(d, r.prompt_bg, p_bg.pixel);
1365 XSetForeground(d, r.completion, compl_fg.pixel);
1366 XSetForeground(d, r.completion_bg, compl_bg.pixel);
1367 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel);
1368 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg.pixel);
1369 XSetForeground(d, r.border_n_bg, border_n_bg.pixel);
1370 XSetForeground(d, r.border_e_bg, border_e_bg.pixel);
1371 XSetForeground(d, r.border_s_bg, border_s_bg.pixel);
1372 XSetForeground(d, r.border_w_bg, border_w_bg.pixel);
1374 // open the X input method
1375 XIM xim = XOpenIM(d, xdb, resname, resclass);
1376 check_allocation(xim);
1378 XIMStyles *xis = nil;
1379 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1380 fprintf(stderr, "Input Styles could not be retrieved\n");
1381 return EX_UNAVAILABLE;
1384 XIMStyle bestMatchStyle = 0;
1385 for (int i = 0; i < xis->count_styles; ++i) {
1386 XIMStyle ts = xis->supported_styles[i];
1387 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1388 bestMatchStyle = ts;
1389 break;
1392 XFree(xis);
1394 if (!bestMatchStyle) {
1395 fprintf(stderr, "No matching input style could be determined\n");
1398 XIC xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
1399 check_allocation(xic);
1401 // draw the window for the first time
1402 draw(&r, text, cs);
1404 // main loop
1405 while (status == LOOPING) {
1406 XEvent e;
1407 XNextEvent(d, &e);
1409 if (XFilterEvent(&e, w))
1410 continue;
1412 switch (e.type) {
1413 case KeymapNotify:
1414 XRefreshKeyboardMapping(&e.xmapping);
1415 break;
1417 case FocusIn:
1418 // re-grab focus
1419 if (e.xfocus.window != w)
1420 grabfocus(d, w);
1421 break;
1423 case VisibilityNotify:
1424 if (e.xvisibility.state != VisibilityUnobscured)
1425 XRaiseWindow(d, w);
1426 break;
1428 case MapNotify:
1429 /* fprintf(stderr, "Map Notify!\n"); */
1430 /* TODO: update the computed window and height! */
1431 /* get_wh(d, &w, width, height); */
1432 draw(&r, text, cs);
1433 break;
1435 case KeyPress: {
1436 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
1438 char *input;
1439 switch (parse_event(d, ev, xic, &input)) {
1440 case EXIT:
1441 status = ERR;
1442 break;
1444 case CONFIRM:
1445 status = OK;
1447 // if first_selected is active and the first completion is
1448 // active be sure to 'expand' the text to match the selection
1449 if (first_selected && cs && cs->selected == 0) {
1450 free(text);
1451 text = strdup(cs->completions->completion);
1452 if (text == nil) {
1453 fprintf(stderr, "Memory allocation error");
1454 status = ERR;
1456 textlen = strlen(text);
1458 break;
1460 case PREV_COMPL: {
1461 complete(cs, first_selected, true, &text, &textlen, &status);
1462 break;
1465 case NEXT_COMPL: {
1466 complete(cs, first_selected, false, &text, &textlen, &status);
1467 break;
1470 case DEL_CHAR:
1471 popc(text, textlen);
1472 update_completions(cs, text, lines, first_selected);
1473 break;
1475 case DEL_WORD: {
1476 // `textlen` is the lenght of the allocated string, not the
1477 // lenght of the ACTUAL string
1478 int p = strlen(text) -1;
1479 if (p > 0) { // delete the current char
1480 text[p] = 0;
1481 p--;
1484 // erase the alphanumeric char
1485 while (p >= 0 && isalnum(text[p])) {
1486 text[p] = 0;
1487 p--;
1490 // erase also trailing white spaces
1491 while (p >= 0 && isspace(text[p])) {
1492 text[p] = 0;
1493 p--;
1495 update_completions(cs, text, lines, first_selected);
1496 break;
1499 case DEL_LINE: {
1500 for (int i = 0; i < textlen; ++i)
1501 text[i] = 0;
1502 update_completions(cs, text, lines, first_selected);
1503 break;
1506 case ADD_CHAR: {
1507 int str_len = strlen(input);
1509 // sometimes a strange key is pressed (i.e. ctrl alone),
1510 // so input will be empty. Don't need to update completion
1511 // in this case
1512 if (str_len == 0)
1513 break;
1515 for (int i = 0; i < str_len; ++i) {
1516 textlen = pushc(&text, textlen, input[i]);
1517 if (textlen == -1) {
1518 fprintf(stderr, "Memory allocation error\n");
1519 status = ERR;
1520 break;
1523 if (status != ERR) {
1524 update_completions(cs, text, lines, first_selected);
1525 free(input);
1527 break;
1530 case TOGGLE_FIRST_SELECTED:
1531 first_selected = !first_selected;
1532 if (first_selected && cs->selected < 0)
1533 cs->selected = 0;
1534 if (!first_selected && cs->selected == 0)
1535 cs->selected = -1;
1536 break;
1541 draw(&r, text, cs);
1544 if (status == OK)
1545 printf("%s\n", text);
1547 release_keyboard(r.d);
1549 #ifdef USE_XFT
1550 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_prompt);
1551 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion);
1552 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion_highlighted);
1553 #endif
1555 free(ps1);
1556 free(fontname);
1557 free(text);
1559 char *l = nil;
1560 char **lns = lines;
1561 while ((l = *lns) != nil) {
1562 free(l);
1563 ++lns;
1566 free(lines);
1567 compls_delete(cs);
1569 XDestroyWindow(r.d, r.w);
1570 XCloseDisplay(r.d);
1572 return status;