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 amount of text until an EOF and store it in
394 // lns. `items` is the capacity of lns. It may increase lns with
395 // `realloc(3)` to store more line. Return the number of lines
396 // read. The last item will always be a NULL pointer. It ignore the
397 // "null" (empty) lines
398 int readlines(char ***lns, int items) {
399 int n = 0;
400 char **lines = *lns;
401 while (true) {
402 size_t linelen = 0;
403 ssize_t l = getline(lines + n, &linelen, stdin);
405 if (l == -1) {
406 break;
409 if (linelen == 0 || lines[n][0] == '\n') {
410 free(lines[n]);
411 lines[n] = nil;
412 continue; // forget about this line
415 strtok(lines[n], "\n"); // get rid of the \n
417 ++n;
419 if (n == items - 1) {
420 items += items >>1;
421 char **l = realloc(lines, sizeof(char*) * items);
422 check_allocation(l);
423 *lns = l;
424 lines = l;
428 n++;
429 lines[n] = nil;
430 return items;
433 // Compute the dimension of the string str once rendered, return the
434 // width and save the width and the height in ret_width and ret_height
435 int text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height) {
436 int height;
437 int width;
438 #ifdef USE_XFT
439 XGlyphInfo gi;
440 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
441 /* height = gi.height; */
442 /* height = (gi.height + (r->font->ascent - r->font->descent)/2) / 2; */
443 /* height = (r->font->ascent - r->font->descent)/2 + gi.height*2; */
444 height = r->font->ascent - r->font->descent;
445 width = gi.width - gi.x;
446 #else
447 XRectangle rect;
448 XmbTextExtents(*r->font, str, len, nil, &rect);
449 height = rect.height;
450 width = rect.width;
451 #endif
452 if (ret_width != nil) *ret_width = width;
453 if (ret_height != nil) *ret_height = height;
454 return width;
457 // Draw the string str
458 void draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt) {
459 #ifdef USE_XFT
460 XftColor xftcolor;
461 if (tt == PROMPT) xftcolor = r->xft_prompt;
462 if (tt == COMPL) xftcolor = r->xft_completion;
463 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
465 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
466 #else
467 GC gc;
468 if (tt == PROMPT) gc = r->prompt;
469 if (tt == COMPL) gc = r->completion;
470 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
471 Xutf8DrawString(r->d, r->w, *r->font, gc, x, y, str, len);
472 #endif
475 // Duplicate the string str and substitute every space with a 'n'
476 char *strdupn(char *str) {
477 int len = strlen(str);
479 if (str == nil || len == 0)
480 return nil;
482 char *dup = strdup(str);
483 if (dup == nil)
484 return nil;
486 for (int i = 0; i < len; ++i)
487 if (dup[i] == ' ')
488 dup[i] = 'n';
490 return dup;
493 // |------------------|----------------------------------------------|
494 // | 20 char text | completion | completion | completion | compl |
495 // |------------------|----------------------------------------------|
496 void draw_horizontally(struct rendering *r, char *text, struct completions *cs) {
497 int prompt_width = 20; // char
499 int width, height;
500 int ps1xlen = text_extents(r->ps1, r->ps1len, r, &width, &height);
501 int start_at = ps1xlen;
503 start_at = r->x_zero + text_extents("n", 1, r, nil, nil);
504 start_at = start_at * prompt_width + r->padding;
506 int texty = (inner_height(r) + height + r->y_zero) / 2;
508 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, start_at, inner_height(r));
510 int text_len = strlen(text);
511 if (text_len > prompt_width)
512 text = text + (text_len - prompt_width);
513 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, texty, r, PROMPT);
514 draw_string(text, MIN(text_len, prompt_width), r->x_zero + r->padding + ps1xlen, texty, r, PROMPT);
516 XFillRectangle(r->d, r->w, r->completion_bg, start_at, r->y_zero, r->width, inner_height(r));
518 struct completion *c = cs->completions;
519 for (int i = 0; c != nil; ++i) {
520 enum text_type tt = cs->selected == i ? COMPL_HIGH : COMPL;
521 GC h = cs->selected == i ? r->completion_highlighted_bg : r->completion_bg;
523 int len = strlen(c->completion);
524 int text_width = text_extents(c->completion, len, r, nil, nil);
526 XFillRectangle(r->d, r->w, h, start_at, r->y_zero, text_width + r->padding*2, inner_height(r));
528 draw_string(c->completion, len, start_at + r->padding, texty, r, tt);
530 start_at += text_width + r->padding * 2;
532 if (start_at > inner_width(r))
533 break; // don't draw completion if the space isn't enough
535 c = c->next;
539 // |-----------------------------------------------------------------|
540 // | prompt |
541 // |-----------------------------------------------------------------|
542 // | completion |
543 // |-----------------------------------------------------------------|
544 // | completion |
545 // |-----------------------------------------------------------------|
546 void draw_vertically(struct rendering *r, char *text, struct completions *cs) {
547 int height, width;
548 text_extents("fjpgl", 5, r, nil, &height);
549 int start_at = r->y_zero + r->padding*2 + height;
551 XFillRectangle(r->d, r->w, r->completion_bg, r->x_zero, r->y_zero, r->width, r->height);
552 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, r->width, start_at);
554 int ps1xlen = text_extents(r->ps1, r->ps1len, r, nil, nil);
556 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, r->y_zero + height + r->padding, r, PROMPT);
557 draw_string(text, strlen(text), r->x_zero + r->padding + ps1xlen, r->y_zero + height + r->padding, r, PROMPT);
559 struct completion *c = cs->completions;
560 for (int i = 0; c != nil; ++i){
561 enum text_type tt = cs->selected == i ? COMPL_HIGH : COMPL;
562 GC h = cs->selected == i ? r->completion_highlighted_bg : r->completion_bg;
564 int len = strlen(c->completion);
565 text_extents(c->completion, len, r, &width, &height);
566 XFillRectangle(r->d, r->w, h, r->x_zero, start_at, inner_width(r), height + r->padding*2);
567 draw_string(c->completion, len, r->x_zero + r->padding, start_at + height + r->padding, r, tt);
569 start_at += height + r->padding *2;
571 if (start_at > inner_height(r))
572 break; // don't draw completion if the space isn't enough
574 c = c->next;
578 void draw(struct rendering *r, char *text, struct completions *cs) {
579 if (r->horizontal_layout)
580 draw_horizontally(r, text, cs);
581 else
582 draw_vertically(r, text, cs);
584 // draw the borders
586 if (r->border_w != 0)
587 XFillRectangle(r->d, r->w, r->border_w_bg, 0, 0, r->border_w, r->height);
589 if (r->border_e != 0)
590 XFillRectangle(r->d, r->w, r->border_e_bg, r->width - r->border_e, 0, r->border_e, r->height);
592 if (r->border_n != 0)
593 XFillRectangle(r->d, r->w, r->border_n_bg, 0, 0, r->width, r->border_n);
595 if (r->border_s != 0)
596 XFillRectangle(r->d, r->w, r->border_s_bg, 0, r->height - r->border_s, r->width, r->border_s);
598 // send all the work to x
599 XFlush(r->d);
602 /* Set some WM stuff */
603 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
604 Atom type;
605 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
606 XChangeProperty(
607 d,
608 w,
609 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
610 XInternAtom(d, "ATOM", false),
611 32,
612 PropModeReplace,
613 (unsigned char *)&type,
615 );
617 /* some window managers honor this properties */
618 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
619 XChangeProperty(d,
620 w,
621 XInternAtom(d, "_NET_WM_STATE", false),
622 XInternAtom(d, "ATOM", false),
623 32,
624 PropModeReplace,
625 (unsigned char *)&type,
627 );
629 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
630 XChangeProperty(d,
631 w,
632 XInternAtom(d, "_NET_WM_STATE", false),
633 XInternAtom(d, "ATOM", false),
634 32,
635 PropModeAppend,
636 (unsigned char *)&type,
638 );
640 // setting window hints
641 XClassHint *class_hint = XAllocClassHint();
642 if (class_hint == nil) {
643 fprintf(stderr, "Could not allocate memory for class hint\n");
644 exit(EX_UNAVAILABLE);
646 class_hint->res_name = resname;
647 class_hint->res_class = resclass;
648 XSetClassHint(d, w, class_hint);
649 XFree(class_hint);
651 XSizeHints *size_hint = XAllocSizeHints();
652 if (size_hint == nil) {
653 fprintf(stderr, "Could not allocate memory for size hint\n");
654 exit(EX_UNAVAILABLE);
656 size_hint->flags = PMinSize | PBaseSize;
657 size_hint->min_width = width;
658 size_hint->base_width = width;
659 size_hint->min_height = height;
660 size_hint->base_height = height;
662 XFlush(d);
665 // write the width and height of the window `w' respectively in `width'
666 // and `height'.
667 void get_wh(Display *d, Window *w, int *width, int *height) {
668 XWindowAttributes win_attr;
669 XGetWindowAttributes(d, *w, &win_attr);
670 *height = win_attr.height;
671 *width = win_attr.width;
674 int grabfocus(Display *d, Window w) {
675 for (int i = 0; i < 100; ++i) {
676 Window focuswin;
677 int revert_to_win;
678 XGetInputFocus(d, &focuswin, &revert_to_win);
679 if (focuswin == w)
680 return true;
681 XSetInputFocus(d, w, RevertToParent, CurrentTime);
682 usleep(1000);
684 return 0;
687 // I know this may seem a little hackish BUT is the only way I managed
688 // to actually grab that goddam keyboard. Only one call to
689 // XGrabKeyboard does not always end up with the keyboard grabbed!
690 int take_keyboard(Display *d, Window w) {
691 int i;
692 for (i = 0; i < 100; i++) {
693 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
694 return 1;
695 usleep(1000);
697 fprintf(stderr, "Cannot grab keyboard\n");
698 return 0;
701 // release the keyboard.
702 void release_keyboard(Display *d) {
703 XUngrabKeyboard(d, CurrentTime);
706 // Given a string, try to parse it as a number or return
707 // `default_value'.
708 int parse_integer(const char *str, int default_value) {
709 errno = 0;
710 char *ep;
711 long lval = strtol(str, &ep, 10);
712 if (str[0] == '\0' || *ep != '\0') { // NaN
713 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
714 return default_value;
716 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
717 (lval > INT_MAX || lval < INT_MIN)) {
718 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
719 return default_value;
721 return lval;
724 // like parse_integer, but if the value ends with a `%' then its
725 // treated like a percentage (`max' is used to compute the percentage)
726 int parse_int_with_percentage(const char *str, int default_value, int max) {
727 int len = strlen(str);
728 if (len > 0 && str[len-1] == '%') {
729 char *cpy = strdup(str);
730 check_allocation(cpy);
731 cpy[len-1] = '\0';
732 int val = parse_integer(cpy, default_value);
733 free(cpy);
734 return val * max / 100;
736 return parse_integer(str, default_value);
739 // like parse_int_with_percentage but understands some special values
740 // - "middle" that is (max - self) / 2
741 // - "start" that is 0
742 // - "end" that is (max - self)
743 int parse_int_with_pos(const char *str, int default_value, int max, int self) {
744 if (!strcmp(str, "start"))
745 return 0;
746 if (!strcmp(str, "middle"))
747 return (max - self)/2;
748 if (!strcmp(str, "end"))
749 return max-self;
750 return parse_int_with_percentage(str, default_value, max);
753 // parse a string like a css value (for example like the css
754 // margin/padding properties). Will ALWAYS return an array of 4 word
755 // TODO: harden this function!
756 char **parse_csslike(const char *str) {
757 char *s = strdup(str);
758 if (s == nil)
759 return nil;
761 char **ret = malloc(4 * sizeof(char*));
762 if (ret == nil) {
763 free(s);
764 return nil;
767 int i = 0;
768 char *token;
769 while ((token = strsep(&s, " ")) != NULL && i < 4) {
770 ret[i] = strdup(token);
771 i++;
774 if (i == 1)
775 for (int j = 1; j < 4; j++)
776 ret[j] = strdup(ret[0]);
778 if (i == 2) {
779 ret[2] = strdup(ret[0]);
780 ret[3] = strdup(ret[1]);
783 if (i == 3)
784 ret[3] = strdup(ret[1]);
786 // Before we didn't check for the return type of strdup, here we will
788 bool any_null = false;
789 for (int i = 0; i < 4; ++i)
790 any_null = ret[i] == nil || any_null;
792 if (any_null)
793 for (int i = 0; i < 4; ++i)
794 if (ret[i] != nil)
795 free(ret[i]);
797 if (i == 0 || any_null) {
798 free(s);
799 free(ret);
800 return nil;
803 return ret;
806 // Given an event, try to understand what the user wants. If the
807 // return value is ADD_CHAR then `input' is a pointer to a string that
808 // will need to be free'ed.
809 enum action parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input) {
810 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
811 return DEL_CHAR;
813 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
814 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
816 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
817 return CONFIRM;
819 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
820 return EXIT;
822 // try to read what the user pressed
823 char str[SYM_BUF_SIZE] = {0};
824 Status s = 0;
825 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
826 if (s == XBufferOverflow) {
827 // should not happen since there are no utf-8 characters larger
828 // than 24bits
829 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
830 return EXIT;
833 if (ev->state & ControlMask) {
834 if (!strcmp(str, "")) // C-u
835 return DEL_LINE;
836 if (!strcmp(str, "")) // C-w
837 return DEL_WORD;
838 if (!strcmp(str, "")) // C-h
839 return DEL_CHAR;
840 if (!strcmp(str, "\r")) // C-m
841 return CONFIRM;
842 if (!strcmp(str, "")) // C-p
843 return PREV_COMPL;
844 if (!strcmp(str, "")) // C-n
845 return NEXT_COMPL;
846 if (!strcmp(str, "")) // C-c
847 return EXIT;
848 if (!strcmp(str, "\t")) // C-i
849 return TOGGLE_FIRST_SELECTED;
852 *input = strdup(str);
853 if (*input == nil) {
854 fprintf(stderr, "Error while allocating memory for key.\n");
855 return EXIT;
858 return ADD_CHAR;
861 // Given the name of the program (argv[0]?) print a small help on stderr
862 void usage(char *prgname) {
863 fprintf(stderr, "%s [-hva] [-p prompt] [-x coord] [-y coord] [-W width] [-H height]\n"
864 " [-P padding] [-l layout] [-f font] [-b borders] [-B colors]\n"
865 " [-t color] [-T color] [-c color] [-C color] [-s color] [-S color]\n"
866 " [-w window_id]\n", prgname);
869 int main(int argc, char **argv) {
870 #ifdef HAVE_PLEDGE
871 // stdio & rpat: to read and write stdio/stdout
872 // unix: to connect to Xorg
873 pledge("stdio rpath unix", "");
874 #endif
876 char *sep = nil;
878 // by default the first completion isn't selected
879 bool first_selected = false;
881 // our parent window
882 char *parent_window_id = nil;
884 // the user can input arbitrary text
885 bool free_text = true;
887 // first round of args parsing
888 int ch;
889 while ((ch = getopt(argc, argv, ARGS)) != -1) {
890 switch (ch) {
891 case 'h': // help
892 usage(*argv);
893 return 0;
894 case 'v': // version
895 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
896 return 0;
897 case 'e': // embed
898 parent_window_id = strdup(optarg);
899 check_allocation(parent_window_id);
900 break;
901 case 'd': {
902 sep = strdup(optarg);
903 check_allocation(sep);
905 case 'A': {
906 free_text = false;
907 break;
909 default:
910 break;
914 // read the lines from stdin
915 char **lines = calloc(INITIAL_ITEMS, sizeof(char*));
916 check_allocation(lines);
917 int nlines = readlines(&lines, INITIAL_ITEMS);
918 char **vlines = nil;
919 if (sep != nil) {
920 int l = strlen(sep);
921 vlines = calloc(nlines, sizeof(char*));
922 check_allocation(vlines);
924 for (int i = 0; lines[i] != nil; i++) {
925 char *t = strstr(lines[i], sep);
926 if (t == nil)
927 vlines[i] = lines[i];
928 else
929 vlines[i] = t + l;
933 setlocale(LC_ALL, getenv("LANG"));
935 enum state status = LOOPING;
937 // where the monitor start (used only with xinerama)
938 int offset_x = 0;
939 int offset_y = 0;
941 // width and height of the window
942 int width = 400;
943 int height = 20;
945 // position on the screen
946 int x = 0;
947 int y = 0;
949 // the default padding
950 int padding = 10;
952 // the default borders
953 int border_n = 0;
954 int border_e = 0;
955 int border_s = 0;
956 int border_w = 0;
958 // the prompt. We duplicate the string so later is easy to free (in
959 // the case the user provide its own prompt)
960 char *ps1 = strdup("$ ");
961 check_allocation(ps1);
963 // same for the font name
964 char *fontname = strdup(default_fontname);
965 check_allocation(fontname);
967 int textlen = 10;
968 char *text = malloc(textlen * sizeof(char));
969 check_allocation(text);
971 /* struct completions *cs = filter(text, lines); */
972 struct completions *cs = compls_new();
973 check_allocation(cs);
975 // start talking to xorg
976 Display *d = XOpenDisplay(nil);
977 if (d == nil) {
978 fprintf(stderr, "Could not open display!\n");
979 return EX_UNAVAILABLE;
982 Window parent_window;
983 bool embed = true;
984 if (! (parent_window_id && (parent_window = strtol(parent_window_id, nil, 0)))) {
985 parent_window = DefaultRootWindow(d);
986 embed = false;
989 // get display size
990 int d_width;
991 int d_height;
992 get_wh(d, &parent_window, &d_width, &d_height);
994 #ifdef USE_XINERAMA
995 if (!embed && XineramaIsActive(d)) {
996 // find the mice
997 int number_of_screens = XScreenCount(d);
998 Window r;
999 Window root;
1000 int root_x, root_y, win_x, win_y;
1001 unsigned int mask;
1002 bool res;
1003 for (int i = 0; i < number_of_screens; ++i) {
1004 root = XRootWindow(d, i);
1005 res = XQueryPointer(d, root, &r, &r, &root_x, &root_y, &win_x, &win_y, &mask);
1006 if (res) break;
1008 if (!res) {
1009 fprintf(stderr, "No mouse found.\n");
1010 root_x = 0;
1011 root_y = 0;
1014 // now find in which monitor the mice is on
1015 int monitors;
1016 XineramaScreenInfo *info = XineramaQueryScreens(d, &monitors);
1017 if (info) {
1018 for (int i = 0; i < monitors; ++i) {
1019 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
1020 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
1021 offset_x = info[i].x_org;
1022 offset_y = info[i].y_org;
1023 d_width = info[i].width;
1024 d_height = info[i].height;
1025 break;
1029 XFree(info);
1031 #endif
1033 Colormap cmap = DefaultColormap(d, DefaultScreen(d));
1034 XColor p_fg, p_bg,
1035 compl_fg, compl_bg,
1036 compl_highlighted_fg, compl_highlighted_bg,
1037 border_n_bg, border_e_bg, border_s_bg, border_w_bg;
1039 bool horizontal_layout = true;
1041 // read resource
1042 XrmInitialize();
1043 char *xrm = XResourceManagerString(d);
1044 XrmDatabase xdb = nil;
1045 if (xrm != nil) {
1046 xdb = XrmGetStringDatabase(xrm);
1047 XrmValue value;
1048 char *datatype[20];
1050 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
1051 fontname = strdup(value.addr);
1052 check_allocation(fontname);
1053 } else {
1054 fprintf(stderr, "no font defined, using %s\n", fontname);
1057 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == true)
1058 horizontal_layout = !strcmp(value.addr, "horizontal");
1059 else
1060 fprintf(stderr, "no layout defined, using horizontal\n");
1062 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == true) {
1063 free(ps1);
1064 ps1 = normalize_str(value.addr);
1065 } else {
1066 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", ps1);
1069 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
1070 width = parse_int_with_percentage(value.addr, width, d_width);
1071 else
1072 fprintf(stderr, "no width defined, using %d\n", width);
1074 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
1075 height = parse_int_with_percentage(value.addr, height, d_height);
1076 else
1077 fprintf(stderr, "no height defined, using %d\n", height);
1079 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
1080 x = parse_int_with_pos(value.addr, x, d_width, width);
1081 else
1082 fprintf(stderr, "no x defined, using %d\n", x);
1084 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
1085 y = parse_int_with_pos(value.addr, y, d_height, height);
1086 else
1087 fprintf(stderr, "no y defined, using %d\n", y);
1089 if (XrmGetResource(xdb, "MyMenu.padding", "*", datatype, &value) == true)
1090 padding = parse_integer(value.addr, padding);
1091 else
1092 fprintf(stderr, "no padding defined, using %d\n", padding);
1094 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value) == true) {
1095 char **borders = parse_csslike(value.addr);
1096 if (borders != nil) {
1097 border_n = parse_integer(borders[0], 0);
1098 border_e = parse_integer(borders[1], 0);
1099 border_s = parse_integer(borders[2], 0);
1100 border_w = parse_integer(borders[3], 0);
1101 } else {
1102 fprintf(stderr, "error while parsing MyMenu.border.size\n");
1104 } else {
1105 fprintf(stderr, "no border defined, using 0.\n");
1108 XColor tmp;
1109 // TODO: tmp needs to be free'd after every allocation?
1111 // prompt
1112 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
1113 XAllocNamedColor(d, cmap, value.addr, &p_fg, &tmp);
1114 else
1115 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
1117 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
1118 XAllocNamedColor(d, cmap, value.addr, &p_bg, &tmp);
1119 else
1120 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
1122 // completion
1123 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
1124 XAllocNamedColor(d, cmap, value.addr, &compl_fg, &tmp);
1125 else
1126 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
1128 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
1129 XAllocNamedColor(d, cmap, value.addr, &compl_bg, &tmp);
1130 else
1131 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
1133 // completion highlighted
1134 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
1135 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_fg, &tmp);
1136 else
1137 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
1139 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
1140 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_bg, &tmp);
1141 else
1142 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
1144 // border
1145 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value) == true) {
1146 char **colors = parse_csslike(value.addr);
1147 if (colors != nil) {
1148 XAllocNamedColor(d, cmap, colors[0], &border_n_bg, &tmp);
1149 XAllocNamedColor(d, cmap, colors[1], &border_e_bg, &tmp);
1150 XAllocNamedColor(d, cmap, colors[2], &border_s_bg, &tmp);
1151 XAllocNamedColor(d, cmap, colors[3], &border_w_bg, &tmp);
1152 } else {
1153 fprintf(stderr, "error while parsing MyMenu.border.color\n");
1155 } else {
1156 XAllocNamedColor(d, cmap, "white", &border_n_bg, &tmp);
1157 XAllocNamedColor(d, cmap, "white", &border_e_bg, &tmp);
1158 XAllocNamedColor(d, cmap, "white", &border_s_bg, &tmp);
1159 XAllocNamedColor(d, cmap, "white", &border_w_bg, &tmp);
1161 } else {
1162 XColor tmp;
1163 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
1164 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
1165 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
1166 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
1167 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
1168 XAllocNamedColor(d, cmap, "white", &border_n_bg, &tmp);
1169 XAllocNamedColor(d, cmap, "white", &border_e_bg, &tmp);
1170 XAllocNamedColor(d, cmap, "white", &border_s_bg, &tmp);
1171 XAllocNamedColor(d, cmap, "white", &border_w_bg, &tmp);
1174 // second round of args parsing
1175 optind = 0; // reset the option index
1176 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1177 switch (ch) {
1178 case 'a':
1179 first_selected = true;
1180 break;
1181 case 'A':
1182 // free_text -- this case was already catched
1183 break;
1184 case 'd':
1185 // separator -- this case was already catched
1186 break;
1187 case 'e':
1188 // (embedding mymenu) this case was already catched.
1189 break;
1190 case 'p': {
1191 char *newprompt = strdup(optarg);
1192 if (newprompt != nil) {
1193 free(ps1);
1194 ps1 = newprompt;
1196 break;
1198 case 'x':
1199 x = parse_int_with_pos(optarg, x, d_width, width);
1200 break;
1201 case 'y':
1202 y = parse_int_with_pos(optarg, y, d_height, height);
1203 break;
1204 case 'P':
1205 padding = parse_integer(optarg, padding);
1206 break;
1207 case 'l':
1208 horizontal_layout = !strcmp(optarg, "horizontal");
1209 break;
1210 case 'f': {
1211 char *newfont = strdup(optarg);
1212 if (newfont != nil) {
1213 free(fontname);
1214 fontname = newfont;
1216 break;
1218 case 'W':
1219 width = parse_int_with_percentage(optarg, width, d_width);
1220 break;
1221 case 'H':
1222 height = parse_int_with_percentage(optarg, height, d_height);
1223 break;
1224 case 'b': {
1225 char **borders = parse_csslike(optarg);
1226 if (borders != nil) {
1227 border_n = parse_integer(borders[0], 0);
1228 border_e = parse_integer(borders[1], 0);
1229 border_s = parse_integer(borders[2], 0);
1230 border_w = parse_integer(borders[3], 0);
1231 } else {
1232 fprintf(stderr, "Error parsing b option\n");
1234 break;
1236 case 'B': {
1237 char **colors = parse_csslike(optarg);
1238 if (colors != nil) {
1239 XColor tmp;
1240 XAllocNamedColor(d, cmap, colors[0], &border_n_bg, &tmp);
1241 XAllocNamedColor(d, cmap, colors[1], &border_e_bg, &tmp);
1242 XAllocNamedColor(d, cmap, colors[2], &border_s_bg, &tmp);
1243 XAllocNamedColor(d, cmap, colors[3], &border_w_bg, &tmp);
1244 } else {
1245 fprintf(stderr, "error while parsing B option\n");
1247 break;
1249 case 't': {
1250 XColor tmp;
1251 XAllocNamedColor(d, cmap, optarg, &p_fg, &tmp);
1252 break;
1254 case 'T': {
1255 XColor tmp;
1256 XAllocNamedColor(d, cmap, optarg, &p_bg, &tmp);
1257 break;
1259 case 'c': {
1260 XColor tmp;
1261 XAllocNamedColor(d, cmap, optarg, &compl_fg, &tmp);
1262 break;
1264 case 'C': {
1265 XColor tmp;
1266 XAllocNamedColor(d, cmap, optarg, &compl_bg, &tmp);
1267 break;
1269 case 's': {
1270 XColor tmp;
1271 XAllocNamedColor(d, cmap, optarg, &compl_highlighted_fg, &tmp);
1272 break;
1274 case 'S': {
1275 XColor tmp;
1276 XAllocNamedColor(d, cmap, optarg, &compl_highlighted_bg, &tmp);
1277 break;
1279 default:
1280 fprintf(stderr, "Unrecognized option %c\n", ch);
1281 status = ERR;
1282 break;
1286 // since only now we know if the first should be selected, update
1287 // the completion here
1288 update_completions(cs, text, lines, vlines, first_selected);
1290 // load the font
1291 #ifdef USE_XFT
1292 XftFont *font = XftFontOpenName(d, DefaultScreen(d), fontname);
1293 #else
1294 char **missing_charset_list;
1295 int missing_charset_count;
1296 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
1297 if (font == nil) {
1298 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1299 return EX_UNAVAILABLE;
1301 #endif
1303 // create the window
1304 XSetWindowAttributes attr;
1305 attr.override_redirect = true;
1306 attr.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
1308 Window w = XCreateWindow(d, // display
1309 parent_window, // parent
1310 x + offset_x, y + offset_y, // x y
1311 width, height, // w h
1312 0, // border width
1313 CopyFromParent, // depth
1314 InputOutput, // class
1315 CopyFromParent, // visual
1316 CWEventMask | CWOverrideRedirect, // value mask (CWBackPixel in the future also?)
1317 &attr);
1319 set_win_atoms_hints(d, w, width, height);
1321 // we want some events
1322 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeymapStateMask);
1323 XMapRaised(d, w);
1325 // if embed, listen for other events as well
1326 if (embed) {
1327 XSelectInput(d, parent_window, FocusChangeMask);
1328 Window *children, parent, root;
1329 unsigned int children_no;
1330 if (XQueryTree(d, parent_window, &root, &parent, &children, &children_no) && children) {
1331 for (unsigned int i = 0; i < children_no && children[i] != w; ++i)
1332 XSelectInput(d, children[i], FocusChangeMask);
1333 XFree(children);
1335 grabfocus(d, w);
1338 // grab keyboard
1339 take_keyboard(d, w);
1341 // Create some graphics contexts
1342 XGCValues values;
1343 /* values.font = font->fid; */
1345 struct rendering r = {
1346 .d = d,
1347 .w = w,
1348 .width = width,
1349 .height = height,
1350 .padding = padding,
1351 .x_zero = border_w,
1352 .y_zero = border_n,
1353 .border_n = border_n,
1354 .border_e = border_e,
1355 .border_s = border_s,
1356 .border_w = border_w,
1357 .horizontal_layout = horizontal_layout,
1358 .ps1 = ps1,
1359 .ps1len = strlen(ps1),
1360 .prompt = XCreateGC(d, w, 0, &values),
1361 .prompt_bg = XCreateGC(d, w, 0, &values),
1362 .completion = XCreateGC(d, w, 0, &values),
1363 .completion_bg = XCreateGC(d, w, 0, &values),
1364 .completion_highlighted = XCreateGC(d, w, 0, &values),
1365 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
1366 .border_n_bg = XCreateGC(d, w, 0, &values),
1367 .border_e_bg = XCreateGC(d, w, 0, &values),
1368 .border_s_bg = XCreateGC(d, w, 0, &values),
1369 .border_w_bg = XCreateGC(d, w, 0, &values),
1370 #ifdef USE_XFT
1371 .font = font,
1372 #else
1373 .font = &font,
1374 #endif
1377 #ifdef USE_XFT
1378 r.xftdraw = XftDrawCreate(d, w, DefaultVisual(d, 0), DefaultColormap(d, 0));
1380 // prompt
1381 XRenderColor xrcolor;
1382 xrcolor.red = p_fg.red;
1383 xrcolor.green = p_fg.red;
1384 xrcolor.blue = p_fg.red;
1385 xrcolor.alpha = 65535;
1386 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_prompt);
1388 // completion
1389 xrcolor.red = compl_fg.red;
1390 xrcolor.green = compl_fg.green;
1391 xrcolor.blue = compl_fg.blue;
1392 xrcolor.alpha = 65535;
1393 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion);
1395 // completion highlighted
1396 xrcolor.red = compl_highlighted_fg.red;
1397 xrcolor.green = compl_highlighted_fg.green;
1398 xrcolor.blue = compl_highlighted_fg.blue;
1399 xrcolor.alpha = 65535;
1400 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion_highlighted);
1401 #endif
1403 // load the colors in our GCs
1404 XSetForeground(d, r.prompt, p_fg.pixel);
1405 XSetForeground(d, r.prompt_bg, p_bg.pixel);
1406 XSetForeground(d, r.completion, compl_fg.pixel);
1407 XSetForeground(d, r.completion_bg, compl_bg.pixel);
1408 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel);
1409 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg.pixel);
1410 XSetForeground(d, r.border_n_bg, border_n_bg.pixel);
1411 XSetForeground(d, r.border_e_bg, border_e_bg.pixel);
1412 XSetForeground(d, r.border_s_bg, border_s_bg.pixel);
1413 XSetForeground(d, r.border_w_bg, border_w_bg.pixel);
1415 // open the X input method
1416 XIM xim = XOpenIM(d, xdb, resname, resclass);
1417 check_allocation(xim);
1419 XIMStyles *xis = nil;
1420 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1421 fprintf(stderr, "Input Styles could not be retrieved\n");
1422 return EX_UNAVAILABLE;
1425 XIMStyle bestMatchStyle = 0;
1426 for (int i = 0; i < xis->count_styles; ++i) {
1427 XIMStyle ts = xis->supported_styles[i];
1428 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1429 bestMatchStyle = ts;
1430 break;
1433 XFree(xis);
1435 if (!bestMatchStyle) {
1436 fprintf(stderr, "No matching input style could be determined\n");
1439 XIC xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
1440 check_allocation(xic);
1442 // draw the window for the first time
1443 draw(&r, text, cs);
1445 // main loop
1446 while (status == LOOPING) {
1447 XEvent e;
1448 XNextEvent(d, &e);
1450 if (XFilterEvent(&e, w))
1451 continue;
1453 switch (e.type) {
1454 case KeymapNotify:
1455 XRefreshKeyboardMapping(&e.xmapping);
1456 break;
1458 case FocusIn:
1459 // re-grab focus
1460 if (e.xfocus.window != w)
1461 grabfocus(d, w);
1462 break;
1464 case VisibilityNotify:
1465 if (e.xvisibility.state != VisibilityUnobscured)
1466 XRaiseWindow(d, w);
1467 break;
1469 case MapNotify:
1470 /* fprintf(stderr, "Map Notify!\n"); */
1471 /* TODO: update the computed window and height! */
1472 /* get_wh(d, &w, width, height); */
1473 draw(&r, text, cs);
1474 break;
1476 case KeyPress: {
1477 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
1479 char *input;
1480 switch (parse_event(d, ev, xic, &input)) {
1481 case EXIT:
1482 status = ERR;
1483 break;
1485 case CONFIRM: {
1486 status = OK;
1487 if ((cs->selected != -1) || (cs->lenght > 0 && first_selected)) {
1488 // if there is something selected expand it and return
1489 int index = cs->selected == -1 ? 0 : cs->selected;
1490 struct completion *c = cs->completions;
1491 while (true) {
1492 if (index == 0)
1493 break;
1494 c = c->next;
1495 index--;
1497 char *t = c->rcompletion;
1498 free(text);
1499 text = strdup(t);
1500 if (text == nil) {
1501 fprintf(stderr, "Memory allocation error\n");
1502 status = ERR;
1504 textlen = strlen(text);
1505 } else {
1506 if (!free_text) {
1507 // cannot accept arbitrary text
1508 status = LOOPING;
1511 break;
1514 case PREV_COMPL: {
1515 complete(cs, first_selected, true, &text, &textlen, &status);
1516 break;
1519 case NEXT_COMPL: {
1520 complete(cs, first_selected, false, &text, &textlen, &status);
1521 break;
1524 case DEL_CHAR:
1525 popc(text);
1526 update_completions(cs, text, lines, vlines, first_selected);
1527 break;
1529 case DEL_WORD: {
1530 popw(text);
1531 update_completions(cs, text, lines, vlines, first_selected);
1532 break;
1535 case DEL_LINE: {
1536 for (int i = 0; i < textlen; ++i)
1537 text[i] = 0;
1538 update_completions(cs, text, lines, vlines, first_selected);
1539 break;
1542 case ADD_CHAR: {
1543 int str_len = strlen(input);
1545 // sometimes a strange key is pressed (i.e. ctrl alone),
1546 // so input will be empty. Don't need to update completion
1547 // in this case
1548 if (str_len == 0)
1549 break;
1551 for (int i = 0; i < str_len; ++i) {
1552 textlen = pushc(&text, textlen, input[i]);
1553 if (textlen == -1) {
1554 fprintf(stderr, "Memory allocation error\n");
1555 status = ERR;
1556 break;
1559 if (status != ERR) {
1560 update_completions(cs, text, lines, vlines, first_selected);
1561 free(input);
1563 break;
1566 case TOGGLE_FIRST_SELECTED:
1567 first_selected = !first_selected;
1568 if (first_selected && cs->selected < 0)
1569 cs->selected = 0;
1570 if (!first_selected && cs->selected == 0)
1571 cs->selected = -1;
1572 break;
1577 draw(&r, text, cs);
1580 if (status == OK)
1581 printf("%s\n", text);
1583 release_keyboard(r.d);
1585 #ifdef USE_XFT
1586 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_prompt);
1587 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion);
1588 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion_highlighted);
1589 #endif
1591 free(ps1);
1592 free(fontname);
1593 free(text);
1595 char *l = nil;
1596 char **lns = lines;
1597 while ((l = *lns) != nil) {
1598 free(l);
1599 ++lns;
1602 free(lines);
1603 free(vlines);
1604 compls_delete(cs);
1606 XDestroyWindow(r.d, r.w);
1607 XCloseDisplay(r.d);
1609 return status != OK;