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 = height + r->padding;
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 start_at += r->padding + r->y_zero;
561 struct completion *c = cs->completions;
562 for (int i = 0; c != nil; ++i){
563 enum text_type tt = cs->selected == i ? COMPL_HIGH : COMPL;
564 GC h = cs->selected == i ? r->completion_highlighted_bg : r->completion_bg;
566 int len = strlen(c->completion);
567 text_extents(c->completion, len, r, &width, &height);
568 XFillRectangle(r->d, r->w, h, r->x_zero, start_at, inner_width(r), height + r->padding*2);
569 draw_string(c->completion, len, r->x_zero + r->padding, start_at + height + r->padding, r, tt);
571 start_at += height + r->padding *2;
573 if (start_at > inner_height(r))
574 break; // don't draw completion if the space isn't enough
576 c = c->next;
580 void draw(struct rendering *r, char *text, struct completions *cs) {
581 if (r->horizontal_layout)
582 draw_horizontally(r, text, cs);
583 else
584 draw_vertically(r, text, cs);
586 // draw the borders
588 if (r->border_w != 0)
589 XFillRectangle(r->d, r->w, r->border_w_bg, 0, 0, r->border_w, r->height);
591 if (r->border_e != 0)
592 XFillRectangle(r->d, r->w, r->border_e_bg, r->width - r->border_e, 0, r->border_e, r->height);
594 if (r->border_n != 0)
595 XFillRectangle(r->d, r->w, r->border_n_bg, 0, 0, r->width, r->border_n);
597 if (r->border_s != 0)
598 XFillRectangle(r->d, r->w, r->border_s_bg, 0, r->height - r->border_s, r->width, r->border_s);
600 // send all the work to x
601 XFlush(r->d);
604 /* Set some WM stuff */
605 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
606 Atom type;
607 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
608 XChangeProperty(
609 d,
610 w,
611 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
612 XInternAtom(d, "ATOM", false),
613 32,
614 PropModeReplace,
615 (unsigned char *)&type,
617 );
619 /* some window managers honor this properties */
620 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
621 XChangeProperty(d,
622 w,
623 XInternAtom(d, "_NET_WM_STATE", false),
624 XInternAtom(d, "ATOM", false),
625 32,
626 PropModeReplace,
627 (unsigned char *)&type,
629 );
631 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
632 XChangeProperty(d,
633 w,
634 XInternAtom(d, "_NET_WM_STATE", false),
635 XInternAtom(d, "ATOM", false),
636 32,
637 PropModeAppend,
638 (unsigned char *)&type,
640 );
642 // setting window hints
643 XClassHint *class_hint = XAllocClassHint();
644 if (class_hint == nil) {
645 fprintf(stderr, "Could not allocate memory for class hint\n");
646 exit(EX_UNAVAILABLE);
648 class_hint->res_name = resname;
649 class_hint->res_class = resclass;
650 XSetClassHint(d, w, class_hint);
651 XFree(class_hint);
653 XSizeHints *size_hint = XAllocSizeHints();
654 if (size_hint == nil) {
655 fprintf(stderr, "Could not allocate memory for size hint\n");
656 exit(EX_UNAVAILABLE);
658 size_hint->flags = PMinSize | PBaseSize;
659 size_hint->min_width = width;
660 size_hint->base_width = width;
661 size_hint->min_height = height;
662 size_hint->base_height = height;
664 XFlush(d);
667 // write the width and height of the window `w' respectively in `width'
668 // and `height'.
669 void get_wh(Display *d, Window *w, int *width, int *height) {
670 XWindowAttributes win_attr;
671 XGetWindowAttributes(d, *w, &win_attr);
672 *height = win_attr.height;
673 *width = win_attr.width;
676 int grabfocus(Display *d, Window w) {
677 for (int i = 0; i < 100; ++i) {
678 Window focuswin;
679 int revert_to_win;
680 XGetInputFocus(d, &focuswin, &revert_to_win);
681 if (focuswin == w)
682 return true;
683 XSetInputFocus(d, w, RevertToParent, CurrentTime);
684 usleep(1000);
686 return 0;
689 // I know this may seem a little hackish BUT is the only way I managed
690 // to actually grab that goddam keyboard. Only one call to
691 // XGrabKeyboard does not always end up with the keyboard grabbed!
692 int take_keyboard(Display *d, Window w) {
693 int i;
694 for (i = 0; i < 100; i++) {
695 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
696 return 1;
697 usleep(1000);
699 fprintf(stderr, "Cannot grab keyboard\n");
700 return 0;
703 // release the keyboard.
704 void release_keyboard(Display *d) {
705 XUngrabKeyboard(d, CurrentTime);
708 // Given a string, try to parse it as a number or return
709 // `default_value'.
710 int parse_integer(const char *str, int default_value) {
711 errno = 0;
712 char *ep;
713 long lval = strtol(str, &ep, 10);
714 if (str[0] == '\0' || *ep != '\0') { // NaN
715 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
716 return default_value;
718 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
719 (lval > INT_MAX || lval < INT_MIN)) {
720 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
721 return default_value;
723 return lval;
726 // like parse_integer, but if the value ends with a `%' then its
727 // treated like a percentage (`max' is used to compute the percentage)
728 int parse_int_with_percentage(const char *str, int default_value, int max) {
729 int len = strlen(str);
730 if (len > 0 && str[len-1] == '%') {
731 char *cpy = strdup(str);
732 check_allocation(cpy);
733 cpy[len-1] = '\0';
734 int val = parse_integer(cpy, default_value);
735 free(cpy);
736 return val * max / 100;
738 return parse_integer(str, default_value);
741 // like parse_int_with_percentage but understands some special values
742 // - "middle" that is (max - self) / 2
743 // - "start" that is 0
744 // - "end" that is (max - self)
745 int parse_int_with_pos(const char *str, int default_value, int max, int self) {
746 if (!strcmp(str, "start"))
747 return 0;
748 if (!strcmp(str, "middle"))
749 return (max - self)/2;
750 if (!strcmp(str, "end"))
751 return max-self;
752 return parse_int_with_percentage(str, default_value, max);
755 // parse a string like a css value (for example like the css
756 // margin/padding properties). Will ALWAYS return an array of 4 word
757 // TODO: harden this function!
758 char **parse_csslike(const char *str) {
759 char *s = strdup(str);
760 if (s == nil)
761 return nil;
763 char **ret = malloc(4 * sizeof(char*));
764 if (ret == nil) {
765 free(s);
766 return nil;
769 int i = 0;
770 char *token;
771 while ((token = strsep(&s, " ")) != NULL && i < 4) {
772 ret[i] = strdup(token);
773 i++;
776 if (i == 1)
777 for (int j = 1; j < 4; j++)
778 ret[j] = strdup(ret[0]);
780 if (i == 2) {
781 ret[2] = strdup(ret[0]);
782 ret[3] = strdup(ret[1]);
785 if (i == 3)
786 ret[3] = strdup(ret[1]);
788 // Before we didn't check for the return type of strdup, here we will
790 bool any_null = false;
791 for (int i = 0; i < 4; ++i)
792 any_null = ret[i] == nil || any_null;
794 if (any_null)
795 for (int i = 0; i < 4; ++i)
796 if (ret[i] != nil)
797 free(ret[i]);
799 if (i == 0 || any_null) {
800 free(s);
801 free(ret);
802 return nil;
805 return ret;
808 // Given an event, try to understand what the user wants. If the
809 // return value is ADD_CHAR then `input' is a pointer to a string that
810 // will need to be free'ed.
811 enum action parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input) {
812 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
813 return DEL_CHAR;
815 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
816 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
818 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
819 return CONFIRM;
821 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
822 return EXIT;
824 // try to read what the user pressed
825 char str[SYM_BUF_SIZE] = {0};
826 Status s = 0;
827 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
828 if (s == XBufferOverflow) {
829 // should not happen since there are no utf-8 characters larger
830 // than 24bits
831 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
832 return EXIT;
835 if (ev->state & ControlMask) {
836 if (!strcmp(str, "")) // C-u
837 return DEL_LINE;
838 if (!strcmp(str, "")) // C-w
839 return DEL_WORD;
840 if (!strcmp(str, "")) // C-h
841 return DEL_CHAR;
842 if (!strcmp(str, "\r")) // C-m
843 return CONFIRM;
844 if (!strcmp(str, "")) // C-p
845 return PREV_COMPL;
846 if (!strcmp(str, "")) // C-n
847 return NEXT_COMPL;
848 if (!strcmp(str, "")) // C-c
849 return EXIT;
850 if (!strcmp(str, "\t")) // C-i
851 return TOGGLE_FIRST_SELECTED;
854 *input = strdup(str);
855 if (*input == nil) {
856 fprintf(stderr, "Error while allocating memory for key.\n");
857 return EXIT;
860 return ADD_CHAR;
863 // Given the name of the program (argv[0]?) print a small help on stderr
864 void usage(char *prgname) {
865 fprintf(stderr, "%s [-hva] [-p prompt] [-x coord] [-y coord] [-W width] [-H height]\n"
866 " [-P padding] [-l layout] [-f font] [-b borders] [-B colors]\n"
867 " [-t color] [-T color] [-c color] [-C color] [-s color] [-S color]\n"
868 " [-w window_id]\n", prgname);
871 int main(int argc, char **argv) {
872 #ifdef HAVE_PLEDGE
873 // stdio & rpat: to read and write stdio/stdout
874 // unix: to connect to Xorg
875 pledge("stdio rpath unix", "");
876 #endif
878 char *sep = nil;
880 // by default the first completion isn't selected
881 bool first_selected = false;
883 // our parent window
884 char *parent_window_id = nil;
886 // the user can input arbitrary text
887 bool free_text = true;
889 // first round of args parsing
890 int ch;
891 while ((ch = getopt(argc, argv, ARGS)) != -1) {
892 switch (ch) {
893 case 'h': // help
894 usage(*argv);
895 return 0;
896 case 'v': // version
897 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
898 return 0;
899 case 'e': // embed
900 parent_window_id = strdup(optarg);
901 check_allocation(parent_window_id);
902 break;
903 case 'd': {
904 sep = strdup(optarg);
905 check_allocation(sep);
907 case 'A': {
908 free_text = false;
909 break;
911 default:
912 break;
916 // read the lines from stdin
917 char **lines = calloc(INITIAL_ITEMS, sizeof(char*));
918 check_allocation(lines);
919 int nlines = readlines(&lines, INITIAL_ITEMS);
920 char **vlines = nil;
921 if (sep != nil) {
922 int l = strlen(sep);
923 vlines = calloc(nlines, sizeof(char*));
924 check_allocation(vlines);
926 for (int i = 0; lines[i] != nil; i++) {
927 char *t = strstr(lines[i], sep);
928 if (t == nil)
929 vlines[i] = lines[i];
930 else
931 vlines[i] = t + l;
935 setlocale(LC_ALL, getenv("LANG"));
937 enum state status = LOOPING;
939 // where the monitor start (used only with xinerama)
940 int offset_x = 0;
941 int offset_y = 0;
943 // width and height of the window
944 int width = 400;
945 int height = 20;
947 // position on the screen
948 int x = 0;
949 int y = 0;
951 // the default padding
952 int padding = 10;
954 // the default borders
955 int border_n = 0;
956 int border_e = 0;
957 int border_s = 0;
958 int border_w = 0;
960 // the prompt. We duplicate the string so later is easy to free (in
961 // the case the user provide its own prompt)
962 char *ps1 = strdup("$ ");
963 check_allocation(ps1);
965 // same for the font name
966 char *fontname = strdup(default_fontname);
967 check_allocation(fontname);
969 int textlen = 10;
970 char *text = malloc(textlen * sizeof(char));
971 check_allocation(text);
973 /* struct completions *cs = filter(text, lines); */
974 struct completions *cs = compls_new();
975 check_allocation(cs);
977 // start talking to xorg
978 Display *d = XOpenDisplay(nil);
979 if (d == nil) {
980 fprintf(stderr, "Could not open display!\n");
981 return EX_UNAVAILABLE;
984 Window parent_window;
985 bool embed = true;
986 if (! (parent_window_id && (parent_window = strtol(parent_window_id, nil, 0)))) {
987 parent_window = DefaultRootWindow(d);
988 embed = false;
991 // get display size
992 int d_width;
993 int d_height;
994 get_wh(d, &parent_window, &d_width, &d_height);
996 #ifdef USE_XINERAMA
997 if (!embed && XineramaIsActive(d)) {
998 // find the mice
999 int number_of_screens = XScreenCount(d);
1000 Window r;
1001 Window root;
1002 int root_x, root_y, win_x, win_y;
1003 unsigned int mask;
1004 bool res;
1005 for (int i = 0; i < number_of_screens; ++i) {
1006 root = XRootWindow(d, i);
1007 res = XQueryPointer(d, root, &r, &r, &root_x, &root_y, &win_x, &win_y, &mask);
1008 if (res) break;
1010 if (!res) {
1011 fprintf(stderr, "No mouse found.\n");
1012 root_x = 0;
1013 root_y = 0;
1016 // now find in which monitor the mice is on
1017 int monitors;
1018 XineramaScreenInfo *info = XineramaQueryScreens(d, &monitors);
1019 if (info) {
1020 for (int i = 0; i < monitors; ++i) {
1021 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
1022 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
1023 offset_x = info[i].x_org;
1024 offset_y = info[i].y_org;
1025 d_width = info[i].width;
1026 d_height = info[i].height;
1027 break;
1031 XFree(info);
1033 #endif
1035 Colormap cmap = DefaultColormap(d, DefaultScreen(d));
1036 XColor p_fg, p_bg,
1037 compl_fg, compl_bg,
1038 compl_highlighted_fg, compl_highlighted_bg,
1039 border_n_bg, border_e_bg, border_s_bg, border_w_bg;
1041 bool horizontal_layout = true;
1043 // read resource
1044 XrmInitialize();
1045 char *xrm = XResourceManagerString(d);
1046 XrmDatabase xdb = nil;
1047 if (xrm != nil) {
1048 xdb = XrmGetStringDatabase(xrm);
1049 XrmValue value;
1050 char *datatype[20];
1052 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
1053 fontname = strdup(value.addr);
1054 check_allocation(fontname);
1055 } else {
1056 fprintf(stderr, "no font defined, using %s\n", fontname);
1059 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == true)
1060 horizontal_layout = !strcmp(value.addr, "horizontal");
1061 else
1062 fprintf(stderr, "no layout defined, using horizontal\n");
1064 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == true) {
1065 free(ps1);
1066 ps1 = normalize_str(value.addr);
1067 } else {
1068 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", ps1);
1071 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
1072 width = parse_int_with_percentage(value.addr, width, d_width);
1073 else
1074 fprintf(stderr, "no width defined, using %d\n", width);
1076 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
1077 height = parse_int_with_percentage(value.addr, height, d_height);
1078 else
1079 fprintf(stderr, "no height defined, using %d\n", height);
1081 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
1082 x = parse_int_with_pos(value.addr, x, d_width, width);
1083 else
1084 fprintf(stderr, "no x defined, using %d\n", x);
1086 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
1087 y = parse_int_with_pos(value.addr, y, d_height, height);
1088 else
1089 fprintf(stderr, "no y defined, using %d\n", y);
1091 if (XrmGetResource(xdb, "MyMenu.padding", "*", datatype, &value) == true)
1092 padding = parse_integer(value.addr, padding);
1093 else
1094 fprintf(stderr, "no padding defined, using %d\n", padding);
1096 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value) == true) {
1097 char **borders = parse_csslike(value.addr);
1098 if (borders != nil) {
1099 border_n = parse_integer(borders[0], 0);
1100 border_e = parse_integer(borders[1], 0);
1101 border_s = parse_integer(borders[2], 0);
1102 border_w = parse_integer(borders[3], 0);
1103 } else {
1104 fprintf(stderr, "error while parsing MyMenu.border.size\n");
1106 } else {
1107 fprintf(stderr, "no border defined, using 0.\n");
1110 XColor tmp;
1111 // TODO: tmp needs to be free'd after every allocation?
1113 // prompt
1114 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
1115 XAllocNamedColor(d, cmap, value.addr, &p_fg, &tmp);
1116 else
1117 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
1119 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
1120 XAllocNamedColor(d, cmap, value.addr, &p_bg, &tmp);
1121 else
1122 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
1124 // completion
1125 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
1126 XAllocNamedColor(d, cmap, value.addr, &compl_fg, &tmp);
1127 else
1128 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
1130 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
1131 XAllocNamedColor(d, cmap, value.addr, &compl_bg, &tmp);
1132 else
1133 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
1135 // completion highlighted
1136 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
1137 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_fg, &tmp);
1138 else
1139 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
1141 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
1142 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_bg, &tmp);
1143 else
1144 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
1146 // border
1147 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value) == true) {
1148 char **colors = parse_csslike(value.addr);
1149 if (colors != nil) {
1150 XAllocNamedColor(d, cmap, colors[0], &border_n_bg, &tmp);
1151 XAllocNamedColor(d, cmap, colors[1], &border_e_bg, &tmp);
1152 XAllocNamedColor(d, cmap, colors[2], &border_s_bg, &tmp);
1153 XAllocNamedColor(d, cmap, colors[3], &border_w_bg, &tmp);
1154 } else {
1155 fprintf(stderr, "error while parsing MyMenu.border.color\n");
1157 } else {
1158 XAllocNamedColor(d, cmap, "white", &border_n_bg, &tmp);
1159 XAllocNamedColor(d, cmap, "white", &border_e_bg, &tmp);
1160 XAllocNamedColor(d, cmap, "white", &border_s_bg, &tmp);
1161 XAllocNamedColor(d, cmap, "white", &border_w_bg, &tmp);
1163 } else {
1164 XColor tmp;
1165 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
1166 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
1167 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
1168 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
1169 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
1170 XAllocNamedColor(d, cmap, "white", &border_n_bg, &tmp);
1171 XAllocNamedColor(d, cmap, "white", &border_e_bg, &tmp);
1172 XAllocNamedColor(d, cmap, "white", &border_s_bg, &tmp);
1173 XAllocNamedColor(d, cmap, "white", &border_w_bg, &tmp);
1176 // second round of args parsing
1177 optind = 0; // reset the option index
1178 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1179 switch (ch) {
1180 case 'a':
1181 first_selected = true;
1182 break;
1183 case 'A':
1184 // free_text -- this case was already catched
1185 break;
1186 case 'd':
1187 // separator -- this case was already catched
1188 break;
1189 case 'e':
1190 // (embedding mymenu) this case was already catched.
1191 break;
1192 case 'p': {
1193 char *newprompt = strdup(optarg);
1194 if (newprompt != nil) {
1195 free(ps1);
1196 ps1 = newprompt;
1198 break;
1200 case 'x':
1201 x = parse_int_with_pos(optarg, x, d_width, width);
1202 break;
1203 case 'y':
1204 y = parse_int_with_pos(optarg, y, d_height, height);
1205 break;
1206 case 'P':
1207 padding = parse_integer(optarg, padding);
1208 break;
1209 case 'l':
1210 horizontal_layout = !strcmp(optarg, "horizontal");
1211 break;
1212 case 'f': {
1213 char *newfont = strdup(optarg);
1214 if (newfont != nil) {
1215 free(fontname);
1216 fontname = newfont;
1218 break;
1220 case 'W':
1221 width = parse_int_with_percentage(optarg, width, d_width);
1222 break;
1223 case 'H':
1224 height = parse_int_with_percentage(optarg, height, d_height);
1225 break;
1226 case 'b': {
1227 char **borders = parse_csslike(optarg);
1228 if (borders != nil) {
1229 border_n = parse_integer(borders[0], 0);
1230 border_e = parse_integer(borders[1], 0);
1231 border_s = parse_integer(borders[2], 0);
1232 border_w = parse_integer(borders[3], 0);
1233 } else {
1234 fprintf(stderr, "Error parsing b option\n");
1236 break;
1238 case 'B': {
1239 char **colors = parse_csslike(optarg);
1240 if (colors != nil) {
1241 XColor tmp;
1242 XAllocNamedColor(d, cmap, colors[0], &border_n_bg, &tmp);
1243 XAllocNamedColor(d, cmap, colors[1], &border_e_bg, &tmp);
1244 XAllocNamedColor(d, cmap, colors[2], &border_s_bg, &tmp);
1245 XAllocNamedColor(d, cmap, colors[3], &border_w_bg, &tmp);
1246 } else {
1247 fprintf(stderr, "error while parsing B option\n");
1249 break;
1251 case 't': {
1252 XColor tmp;
1253 XAllocNamedColor(d, cmap, optarg, &p_fg, &tmp);
1254 break;
1256 case 'T': {
1257 XColor tmp;
1258 XAllocNamedColor(d, cmap, optarg, &p_bg, &tmp);
1259 break;
1261 case 'c': {
1262 XColor tmp;
1263 XAllocNamedColor(d, cmap, optarg, &compl_fg, &tmp);
1264 break;
1266 case 'C': {
1267 XColor tmp;
1268 XAllocNamedColor(d, cmap, optarg, &compl_bg, &tmp);
1269 break;
1271 case 's': {
1272 XColor tmp;
1273 XAllocNamedColor(d, cmap, optarg, &compl_highlighted_fg, &tmp);
1274 break;
1276 case 'S': {
1277 XColor tmp;
1278 XAllocNamedColor(d, cmap, optarg, &compl_highlighted_bg, &tmp);
1279 break;
1281 default:
1282 fprintf(stderr, "Unrecognized option %c\n", ch);
1283 status = ERR;
1284 break;
1288 // since only now we know if the first should be selected, update
1289 // the completion here
1290 update_completions(cs, text, lines, vlines, first_selected);
1292 // load the font
1293 #ifdef USE_XFT
1294 XftFont *font = XftFontOpenName(d, DefaultScreen(d), fontname);
1295 #else
1296 char **missing_charset_list;
1297 int missing_charset_count;
1298 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
1299 if (font == nil) {
1300 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1301 return EX_UNAVAILABLE;
1303 #endif
1305 // create the window
1306 XSetWindowAttributes attr;
1307 attr.override_redirect = true;
1308 attr.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
1310 Window w = XCreateWindow(d, // display
1311 parent_window, // parent
1312 x + offset_x, y + offset_y, // x y
1313 width, height, // w h
1314 0, // border width
1315 CopyFromParent, // depth
1316 InputOutput, // class
1317 CopyFromParent, // visual
1318 CWEventMask | CWOverrideRedirect, // value mask (CWBackPixel in the future also?)
1319 &attr);
1321 set_win_atoms_hints(d, w, width, height);
1323 // we want some events
1324 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeymapStateMask);
1325 XMapRaised(d, w);
1327 // if embed, listen for other events as well
1328 if (embed) {
1329 XSelectInput(d, parent_window, FocusChangeMask);
1330 Window *children, parent, root;
1331 unsigned int children_no;
1332 if (XQueryTree(d, parent_window, &root, &parent, &children, &children_no) && children) {
1333 for (unsigned int i = 0; i < children_no && children[i] != w; ++i)
1334 XSelectInput(d, children[i], FocusChangeMask);
1335 XFree(children);
1337 grabfocus(d, w);
1340 // grab keyboard
1341 take_keyboard(d, w);
1343 // Create some graphics contexts
1344 XGCValues values;
1345 /* values.font = font->fid; */
1347 struct rendering r = {
1348 .d = d,
1349 .w = w,
1350 .width = width,
1351 .height = height,
1352 .padding = padding,
1353 .x_zero = border_w,
1354 .y_zero = border_n,
1355 .border_n = border_n,
1356 .border_e = border_e,
1357 .border_s = border_s,
1358 .border_w = border_w,
1359 .horizontal_layout = horizontal_layout,
1360 .ps1 = ps1,
1361 .ps1len = strlen(ps1),
1362 .prompt = XCreateGC(d, w, 0, &values),
1363 .prompt_bg = XCreateGC(d, w, 0, &values),
1364 .completion = XCreateGC(d, w, 0, &values),
1365 .completion_bg = XCreateGC(d, w, 0, &values),
1366 .completion_highlighted = XCreateGC(d, w, 0, &values),
1367 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
1368 .border_n_bg = XCreateGC(d, w, 0, &values),
1369 .border_e_bg = XCreateGC(d, w, 0, &values),
1370 .border_s_bg = XCreateGC(d, w, 0, &values),
1371 .border_w_bg = XCreateGC(d, w, 0, &values),
1372 #ifdef USE_XFT
1373 .font = font,
1374 #else
1375 .font = &font,
1376 #endif
1379 #ifdef USE_XFT
1380 r.xftdraw = XftDrawCreate(d, w, DefaultVisual(d, 0), DefaultColormap(d, 0));
1382 // prompt
1383 XRenderColor xrcolor;
1384 xrcolor.red = p_fg.red;
1385 xrcolor.green = p_fg.red;
1386 xrcolor.blue = p_fg.red;
1387 xrcolor.alpha = 65535;
1388 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_prompt);
1390 // completion
1391 xrcolor.red = compl_fg.red;
1392 xrcolor.green = compl_fg.green;
1393 xrcolor.blue = compl_fg.blue;
1394 xrcolor.alpha = 65535;
1395 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion);
1397 // completion highlighted
1398 xrcolor.red = compl_highlighted_fg.red;
1399 xrcolor.green = compl_highlighted_fg.green;
1400 xrcolor.blue = compl_highlighted_fg.blue;
1401 xrcolor.alpha = 65535;
1402 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion_highlighted);
1403 #endif
1405 // load the colors in our GCs
1406 XSetForeground(d, r.prompt, p_fg.pixel);
1407 XSetForeground(d, r.prompt_bg, p_bg.pixel);
1408 XSetForeground(d, r.completion, compl_fg.pixel);
1409 XSetForeground(d, r.completion_bg, compl_bg.pixel);
1410 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel);
1411 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg.pixel);
1412 XSetForeground(d, r.border_n_bg, border_n_bg.pixel);
1413 XSetForeground(d, r.border_e_bg, border_e_bg.pixel);
1414 XSetForeground(d, r.border_s_bg, border_s_bg.pixel);
1415 XSetForeground(d, r.border_w_bg, border_w_bg.pixel);
1417 // open the X input method
1418 XIM xim = XOpenIM(d, xdb, resname, resclass);
1419 check_allocation(xim);
1421 XIMStyles *xis = nil;
1422 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1423 fprintf(stderr, "Input Styles could not be retrieved\n");
1424 return EX_UNAVAILABLE;
1427 XIMStyle bestMatchStyle = 0;
1428 for (int i = 0; i < xis->count_styles; ++i) {
1429 XIMStyle ts = xis->supported_styles[i];
1430 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1431 bestMatchStyle = ts;
1432 break;
1435 XFree(xis);
1437 if (!bestMatchStyle) {
1438 fprintf(stderr, "No matching input style could be determined\n");
1441 XIC xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
1442 check_allocation(xic);
1444 // draw the window for the first time
1445 draw(&r, text, cs);
1447 // main loop
1448 while (status == LOOPING) {
1449 XEvent e;
1450 XNextEvent(d, &e);
1452 if (XFilterEvent(&e, w))
1453 continue;
1455 switch (e.type) {
1456 case KeymapNotify:
1457 XRefreshKeyboardMapping(&e.xmapping);
1458 break;
1460 case FocusIn:
1461 // re-grab focus
1462 if (e.xfocus.window != w)
1463 grabfocus(d, w);
1464 break;
1466 case VisibilityNotify:
1467 if (e.xvisibility.state != VisibilityUnobscured)
1468 XRaiseWindow(d, w);
1469 break;
1471 case MapNotify:
1472 /* fprintf(stderr, "Map Notify!\n"); */
1473 /* TODO: update the computed window and height! */
1474 /* get_wh(d, &w, width, height); */
1475 draw(&r, text, cs);
1476 break;
1478 case KeyPress: {
1479 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
1481 char *input;
1482 switch (parse_event(d, ev, xic, &input)) {
1483 case EXIT:
1484 status = ERR;
1485 break;
1487 case CONFIRM: {
1488 status = OK;
1489 if ((cs->selected != -1) || (cs->lenght > 0 && first_selected)) {
1490 // if there is something selected expand it and return
1491 int index = cs->selected == -1 ? 0 : cs->selected;
1492 struct completion *c = cs->completions;
1493 while (true) {
1494 if (index == 0)
1495 break;
1496 c = c->next;
1497 index--;
1499 char *t = c->rcompletion;
1500 free(text);
1501 text = strdup(t);
1502 if (text == nil) {
1503 fprintf(stderr, "Memory allocation error\n");
1504 status = ERR;
1506 textlen = strlen(text);
1507 } else {
1508 if (!free_text) {
1509 // cannot accept arbitrary text
1510 status = LOOPING;
1513 break;
1516 case PREV_COMPL: {
1517 complete(cs, first_selected, true, &text, &textlen, &status);
1518 break;
1521 case NEXT_COMPL: {
1522 complete(cs, first_selected, false, &text, &textlen, &status);
1523 break;
1526 case DEL_CHAR:
1527 popc(text);
1528 update_completions(cs, text, lines, vlines, first_selected);
1529 break;
1531 case DEL_WORD: {
1532 popw(text);
1533 update_completions(cs, text, lines, vlines, first_selected);
1534 break;
1537 case DEL_LINE: {
1538 for (int i = 0; i < textlen; ++i)
1539 text[i] = 0;
1540 update_completions(cs, text, lines, vlines, first_selected);
1541 break;
1544 case ADD_CHAR: {
1545 int str_len = strlen(input);
1547 // sometimes a strange key is pressed (i.e. ctrl alone),
1548 // so input will be empty. Don't need to update completion
1549 // in this case
1550 if (str_len == 0)
1551 break;
1553 for (int i = 0; i < str_len; ++i) {
1554 textlen = pushc(&text, textlen, input[i]);
1555 if (textlen == -1) {
1556 fprintf(stderr, "Memory allocation error\n");
1557 status = ERR;
1558 break;
1561 if (status != ERR) {
1562 update_completions(cs, text, lines, vlines, first_selected);
1563 free(input);
1565 break;
1568 case TOGGLE_FIRST_SELECTED:
1569 first_selected = !first_selected;
1570 if (first_selected && cs->selected < 0)
1571 cs->selected = 0;
1572 if (!first_selected && cs->selected == 0)
1573 cs->selected = -1;
1574 break;
1579 draw(&r, text, cs);
1582 if (status == OK)
1583 printf("%s\n", text);
1585 release_keyboard(r.d);
1587 #ifdef USE_XFT
1588 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_prompt);
1589 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion);
1590 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion_highlighted);
1591 #endif
1593 free(ps1);
1594 free(fontname);
1595 free(text);
1597 char *l = nil;
1598 char **lns = lines;
1599 while ((l = *lns) != nil) {
1600 free(l);
1601 ++lns;
1604 free(lines);
1605 free(vlines);
1606 compls_delete(cs);
1608 XDestroyWindow(r.d, r.w);
1609 XCloseDisplay(r.d);
1611 return status != OK;