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 size_t offset; // a scrolling offset
102 // The four border
103 int border_n;
104 int border_e;
105 int border_s;
106 int border_w;
108 bool horizontal_layout;
110 // the prompt
111 char *ps1;
112 int ps1len;
114 // colors
115 GC prompt;
116 GC prompt_bg;
117 GC completion;
118 GC completion_bg;
119 GC completion_highlighted;
120 GC completion_highlighted_bg;
121 GC border_n_bg;
122 GC border_e_bg;
123 GC border_s_bg;
124 GC border_w_bg;
125 #ifdef USE_XFT
126 XftFont *font;
127 XftDraw *xftdraw;
128 XftColor xft_prompt;
129 XftColor xft_completion;
130 XftColor xft_completion_highlighted;
131 #else
132 XFontSet *font;
133 #endif
134 };
136 struct completion {
137 char *completion;
138 char *rcompletion;
139 };
141 // Wrap the linked list of completions
142 struct completions {
143 struct completion *completions;
144 ssize_t selected;
145 size_t lenght;
146 };
148 // return a newly allocated (and empty) completion list
149 struct completions *compls_new(size_t lenght) {
150 struct completions *cs = malloc(sizeof(struct completions));
152 if (cs == nil)
153 return cs;
155 cs->completions = calloc(lenght, sizeof(struct completion));
156 cs->selected = -1;
157 cs->lenght = lenght;
158 return cs;
161 // Delete the wrapper and the whole list
162 void compls_delete(struct completions *cs) {
163 if (cs == nil)
164 return;
166 free(cs->completions);
167 free(cs);
170 // create a completion list from a text and the list of possible
171 // completions (null terminated). Expects a non-null `cs'. lines and
172 // vlines should have the same lenght OR vlines is null
173 void filter(struct completions *cs, char *text, char **lines, char **vlines) {
174 size_t index = 0;
175 size_t matching = 0;
177 if (vlines == nil)
178 vlines = lines;
180 while (true) {
181 char *l = vlines[index] != nil ? vlines[index] : lines[index];
182 if (l == nil)
183 break;
185 if (strcasestr(l, text) != nil) {
186 struct completion *c = &cs->completions[matching];
187 c->completion = l;
188 c->rcompletion = lines[index];
189 matching++;
192 index++;
194 cs->lenght = matching;
195 cs->selected = -1;
198 // update the given completion, that is: clean the old cs & generate a new one.
199 void update_completions(struct completions *cs, char *text, char **lines, char **vlines, bool first_selected) {
200 filter(cs, text, lines, vlines);
201 if (first_selected && cs->lenght > 0)
202 cs->selected = 0;
205 // select the next, or the previous, selection and update some
206 // state. `text' will be updated with the text of the completion and
207 // `textlen' with the new lenght of `text'. If the memory cannot be
208 // allocated, `status' will be set to `ERR'.
209 void complete(struct completions *cs, bool first_selected, bool p, char **text, int *textlen, enum state *status) {
210 if (cs == nil || cs->lenght == 0)
211 return;
213 // if the first is always selected, and the first entry is different
214 // from the text, expand the text and return
215 if (first_selected
216 && cs->selected == 0
217 && strcmp(cs->completions->completion, *text) != 0
218 && !p) {
219 free(*text);
220 *text = strdup(cs->completions->completion);
221 if (text == nil) {
222 *status = ERR;
223 return;
225 *textlen = strlen(*text);
226 return;
229 int index = cs->selected;
231 if (index == -1 && p)
232 index = 0;
233 index = cs->selected = (cs->lenght + (p ? index - 1 : index + 1)) % cs->lenght;
235 struct completion *n = &cs->completions[cs->selected];
237 free(*text);
238 *text = strdup(n->completion);
239 if (text == nil) {
240 fprintf(stderr, "Memory allocation error!\n");
241 *status = ERR;
242 return;
244 *textlen = strlen(*text);
247 // push the character c at the end of the string pointed by p
248 int pushc(char **p, int maxlen, char c) {
249 int len = strnlen(*p, maxlen);
251 if (!(len < maxlen -2)) {
252 maxlen += maxlen >> 1;
253 char *newptr = realloc(*p, maxlen);
254 if (newptr == nil) { // bad!
255 return -1;
257 *p = newptr;
260 (*p)[len] = c;
261 (*p)[len+1] = '\0';
262 return maxlen;
265 // remove the last rune from the *utf8* string! This is different from
266 // just setting the last byte to 0 (in some cases ofc). Return a
267 // pointer (e) to the last non zero char. If e < p then p is empty!
268 char* popc(char *p) {
269 int len = strlen(p);
270 if (len == 0)
271 return p;
273 char *e = p + len - 1;
275 do {
276 char c = *e;
277 *e = 0;
278 e--;
280 // if c is a starting byte (11......) or is under U+007F (ascii,
281 // basically) we're done
282 if (((c & 0x80) && (c & 0x40)) || !(c & 0x80))
283 break;
284 } while (e >= p);
286 return e;
289 // remove the last word plus trailing whitespaces from the give string
290 void popw(char *w) {
291 int len = strlen(w);
292 if (len == 0)
293 return;
295 bool in_word = true;
296 while (true) {
297 char *e = popc(w);
299 if (e < w)
300 return;
302 if (in_word && isspace(*e))
303 in_word = false;
305 if (!in_word && !isspace(*e))
306 return;
310 // If the string is surrounded by quotes (`"`) remove them and replace
311 // every `\"` in the string with `"`
312 char *normalize_str(const char *str) {
313 int len = strlen(str);
314 if (len == 0)
315 return nil;
317 char *s = calloc(len, sizeof(char));
318 check_allocation(s);
319 int p = 0;
320 while (*str) {
321 char c = *str;
322 if (*str == '\\') {
323 if (*(str + 1)) {
324 s[p] = *(str + 1);
325 p++;
326 str += 2; // skip this and the next char
327 continue;
328 } else {
329 break;
332 if (c == '"') {
333 str++; // skip only this char
334 continue;
336 s[p] = c;
337 p++;
338 str++;
340 return s;
343 // read an arbitrary amount of text until an EOF and store it in
344 // lns. `items` is the capacity of lns. It may increase lns with
345 // `realloc(3)` to store more line. Return the number of lines
346 // read. The last item will always be a NULL pointer. It ignore the
347 // "null" (empty) lines
348 size_t readlines(char ***lns, size_t items) {
349 size_t n = 0;
350 char **lines = *lns;
351 while (true) {
352 size_t linelen = 0;
353 ssize_t l = getline(lines + n, &linelen, stdin);
355 if (l == -1) {
356 break;
359 if (linelen == 0 || lines[n][0] == '\n') {
360 free(lines[n]);
361 lines[n] = nil;
362 continue; // forget about this line
365 strtok(lines[n], "\n"); // get rid of the \n
367 ++n;
369 if (n == items - 1) {
370 items += items >>1;
371 char **l = realloc(lines, sizeof(char*) * items);
372 check_allocation(l);
373 *lns = l;
374 lines = l;
378 n++;
379 lines[n] = nil;
380 return items;
383 // Compute the dimension of the string str once rendered, return the
384 // width and save the width and the height in ret_width and ret_height
385 int text_extents(char *str, int len, struct rendering *r, int *ret_width, int *ret_height) {
386 int height;
387 int width;
388 #ifdef USE_XFT
389 XGlyphInfo gi;
390 XftTextExtentsUtf8(r->d, r->font, str, len, &gi);
391 height = r->font->ascent - r->font->descent;
392 width = gi.width - gi.x;
393 #else
394 XRectangle rect;
395 XmbTextExtents(*r->font, str, len, nil, &rect);
396 height = rect.height;
397 width = rect.width;
398 #endif
399 if (ret_width != nil) *ret_width = width;
400 if (ret_height != nil) *ret_height = height;
401 return width;
404 // Draw the string str
405 void draw_string(char *str, int len, int x, int y, struct rendering *r, enum text_type tt) {
406 #ifdef USE_XFT
407 XftColor xftcolor;
408 if (tt == PROMPT) xftcolor = r->xft_prompt;
409 if (tt == COMPL) xftcolor = r->xft_completion;
410 if (tt == COMPL_HIGH) xftcolor = r->xft_completion_highlighted;
412 XftDrawStringUtf8(r->xftdraw, &xftcolor, r->font, x, y, str, len);
413 #else
414 GC gc;
415 if (tt == PROMPT) gc = r->prompt;
416 if (tt == COMPL) gc = r->completion;
417 if (tt == COMPL_HIGH) gc = r->completion_highlighted;
418 Xutf8DrawString(r->d, r->w, *r->font, gc, x, y, str, len);
419 #endif
422 // Duplicate the string str and substitute every space with a 'n'
423 char *strdupn(char *str) {
424 int len = strlen(str);
426 if (str == nil || len == 0)
427 return nil;
429 char *dup = strdup(str);
430 if (dup == nil)
431 return nil;
433 for (int i = 0; i < len; ++i)
434 if (dup[i] == ' ')
435 dup[i] = 'n';
437 return dup;
440 // |------------------|----------------------------------------------|
441 // | 20 char text | completion | completion | completion | compl |
442 // |------------------|----------------------------------------------|
443 void draw_horizontally(struct rendering *r, char *text, struct completions *cs) {
444 int prompt_width = 20; // char
446 int width, height;
447 int ps1xlen = text_extents(r->ps1, r->ps1len, r, &width, &height);
448 int start_at = ps1xlen;
450 start_at = r->x_zero + text_extents("n", 1, r, nil, nil);
451 start_at = start_at * prompt_width + r->padding;
453 int texty = (inner_height(r) + height + r->y_zero) / 2;
455 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, start_at, inner_height(r));
457 int text_len = strlen(text);
458 if (text_len > prompt_width)
459 text = text + (text_len - prompt_width);
460 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, texty, r, PROMPT);
461 draw_string(text, MIN(text_len, prompt_width), r->x_zero + r->padding + ps1xlen, texty, r, PROMPT);
463 XFillRectangle(r->d, r->w, r->completion_bg, start_at, r->y_zero, r->width, inner_height(r));
465 for (size_t i = r->offset; i < cs->lenght; ++i) {
466 struct completion *c = &cs->completions[i];
468 enum text_type tt = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
469 GC h = cs->selected == (ssize_t)i ? r->completion_highlighted_bg : r->completion_bg;
471 int len = strlen(c->completion);
472 int text_width = text_extents(c->completion, len, r, nil, nil);
474 XFillRectangle(r->d, r->w, h, start_at, r->y_zero, text_width + r->padding*2, inner_height(r));
476 draw_string(c->completion, len, start_at + r->padding, texty, r, tt);
478 start_at += text_width + r->padding * 2;
480 if (start_at > inner_width(r))
481 break; // don't draw completion if the space isn't enough
485 // |-----------------------------------------------------------------|
486 // | prompt |
487 // |-----------------------------------------------------------------|
488 // | completion |
489 // |-----------------------------------------------------------------|
490 // | completion |
491 // |-----------------------------------------------------------------|
492 void draw_vertically(struct rendering *r, char *text, struct completions *cs) {
493 int height, width;
494 text_extents("fjpgl", 5, r, nil, &height);
495 int start_at = r->padding*2 + height;
497 XFillRectangle(r->d, r->w, r->completion_bg, r->x_zero, r->y_zero, r->width, r->height);
498 XFillRectangle(r->d, r->w, r->prompt_bg, r->x_zero, r->y_zero, r->width, start_at);
500 int ps1xlen = text_extents(r->ps1, r->ps1len, r, nil, nil);
502 draw_string(r->ps1, r->ps1len, r->x_zero + r->padding, r->y_zero + height + r->padding, r, PROMPT);
503 draw_string(text, strlen(text), r->x_zero + r->padding + ps1xlen, r->y_zero + height + r->padding, r, PROMPT);
505 start_at += r->y_zero;
507 for (size_t i = r->offset; i < cs->lenght; ++i){
508 struct completion *c = &cs->completions[i];
509 enum text_type tt = cs->selected == (ssize_t)i ? COMPL_HIGH : COMPL;
510 GC h = cs->selected == (ssize_t)i ? r->completion_highlighted_bg : r->completion_bg;
512 int len = strlen(c->completion);
513 text_extents(c->completion, len, r, &width, &height);
514 XFillRectangle(r->d, r->w, h, r->x_zero, start_at, inner_width(r), height + r->padding*2);
515 draw_string(c->completion, len, r->x_zero + r->padding, start_at + height + r->padding, r, tt);
517 start_at += height + r->padding *2;
519 if (start_at > inner_height(r))
520 break; // don't draw completion if the space isn't enough
524 void draw(struct rendering *r, char *text, struct completions *cs) {
525 if (r->horizontal_layout)
526 draw_horizontally(r, text, cs);
527 else
528 draw_vertically(r, text, cs);
530 // draw the borders
532 if (r->border_w != 0)
533 XFillRectangle(r->d, r->w, r->border_w_bg, 0, 0, r->border_w, r->height);
535 if (r->border_e != 0)
536 XFillRectangle(r->d, r->w, r->border_e_bg, r->width - r->border_e, 0, r->border_e, r->height);
538 if (r->border_n != 0)
539 XFillRectangle(r->d, r->w, r->border_n_bg, 0, 0, r->width, r->border_n);
541 if (r->border_s != 0)
542 XFillRectangle(r->d, r->w, r->border_s_bg, 0, r->height - r->border_s, r->width, r->border_s);
544 // send all the work to x
545 XFlush(r->d);
548 /* Set some WM stuff */
549 void set_win_atoms_hints(Display *d, Window w, int width, int height) {
550 Atom type;
551 type = XInternAtom(d, "_NET_WM_WINDOW_TYPE_DOCK", false);
552 XChangeProperty(
553 d,
554 w,
555 XInternAtom(d, "_NET_WM_WINDOW_TYPE", false),
556 XInternAtom(d, "ATOM", false),
557 32,
558 PropModeReplace,
559 (unsigned char *)&type,
561 );
563 /* some window managers honor this properties */
564 type = XInternAtom(d, "_NET_WM_STATE_ABOVE", false);
565 XChangeProperty(d,
566 w,
567 XInternAtom(d, "_NET_WM_STATE", false),
568 XInternAtom(d, "ATOM", false),
569 32,
570 PropModeReplace,
571 (unsigned char *)&type,
573 );
575 type = XInternAtom(d, "_NET_WM_STATE_FOCUSED", false);
576 XChangeProperty(d,
577 w,
578 XInternAtom(d, "_NET_WM_STATE", false),
579 XInternAtom(d, "ATOM", false),
580 32,
581 PropModeAppend,
582 (unsigned char *)&type,
584 );
586 // setting window hints
587 XClassHint *class_hint = XAllocClassHint();
588 if (class_hint == nil) {
589 fprintf(stderr, "Could not allocate memory for class hint\n");
590 exit(EX_UNAVAILABLE);
592 class_hint->res_name = resname;
593 class_hint->res_class = resclass;
594 XSetClassHint(d, w, class_hint);
595 XFree(class_hint);
597 XSizeHints *size_hint = XAllocSizeHints();
598 if (size_hint == nil) {
599 fprintf(stderr, "Could not allocate memory for size hint\n");
600 exit(EX_UNAVAILABLE);
602 size_hint->flags = PMinSize | PBaseSize;
603 size_hint->min_width = width;
604 size_hint->base_width = width;
605 size_hint->min_height = height;
606 size_hint->base_height = height;
608 XFlush(d);
611 // write the width and height of the window `w' respectively in `width'
612 // and `height'.
613 void get_wh(Display *d, Window *w, int *width, int *height) {
614 XWindowAttributes win_attr;
615 XGetWindowAttributes(d, *w, &win_attr);
616 *height = win_attr.height;
617 *width = win_attr.width;
620 int grabfocus(Display *d, Window w) {
621 for (int i = 0; i < 100; ++i) {
622 Window focuswin;
623 int revert_to_win;
624 XGetInputFocus(d, &focuswin, &revert_to_win);
625 if (focuswin == w)
626 return true;
627 XSetInputFocus(d, w, RevertToParent, CurrentTime);
628 usleep(1000);
630 return 0;
633 // I know this may seem a little hackish BUT is the only way I managed
634 // to actually grab that goddam keyboard. Only one call to
635 // XGrabKeyboard does not always end up with the keyboard grabbed!
636 int take_keyboard(Display *d, Window w) {
637 int i;
638 for (i = 0; i < 100; i++) {
639 if (XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
640 return 1;
641 usleep(1000);
643 fprintf(stderr, "Cannot grab keyboard\n");
644 return 0;
647 // release the keyboard.
648 void release_keyboard(Display *d) {
649 XUngrabKeyboard(d, CurrentTime);
652 // Given a string, try to parse it as a number or return
653 // `default_value'.
654 int parse_integer(const char *str, int default_value) {
655 errno = 0;
656 char *ep;
657 long lval = strtol(str, &ep, 10);
658 if (str[0] == '\0' || *ep != '\0') { // NaN
659 fprintf(stderr, "'%s' is not a valid number! Using %d as default.\n", str, default_value);
660 return default_value;
662 if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
663 (lval > INT_MAX || lval < INT_MIN)) {
664 fprintf(stderr, "%s out of range! Using %d as default.\n", str, default_value);
665 return default_value;
667 return lval;
670 // like parse_integer, but if the value ends with a `%' then its
671 // treated like a percentage (`max' is used to compute the percentage)
672 int parse_int_with_percentage(const char *str, int default_value, int max) {
673 int len = strlen(str);
674 if (len > 0 && str[len-1] == '%') {
675 char *cpy = strdup(str);
676 check_allocation(cpy);
677 cpy[len-1] = '\0';
678 int val = parse_integer(cpy, default_value);
679 free(cpy);
680 return val * max / 100;
682 return parse_integer(str, default_value);
685 // like parse_int_with_percentage but understands some special values
686 // - "middle" that is (max - self) / 2
687 // - "start" that is 0
688 // - "end" that is (max - self)
689 int parse_int_with_pos(const char *str, int default_value, int max, int self) {
690 if (!strcmp(str, "start"))
691 return 0;
692 if (!strcmp(str, "middle"))
693 return (max - self)/2;
694 if (!strcmp(str, "end"))
695 return max-self;
696 return parse_int_with_percentage(str, default_value, max);
699 // parse a string like a css value (for example like the css
700 // margin/padding properties). Will ALWAYS return an array of 4 word
701 // TODO: harden this function!
702 char **parse_csslike(const char *str) {
703 char *s = strdup(str);
704 if (s == nil)
705 return nil;
707 char **ret = malloc(4 * sizeof(char*));
708 if (ret == nil) {
709 free(s);
710 return nil;
713 int i = 0;
714 char *token;
715 while ((token = strsep(&s, " ")) != NULL && i < 4) {
716 ret[i] = strdup(token);
717 i++;
720 if (i == 1)
721 for (int j = 1; j < 4; j++)
722 ret[j] = strdup(ret[0]);
724 if (i == 2) {
725 ret[2] = strdup(ret[0]);
726 ret[3] = strdup(ret[1]);
729 if (i == 3)
730 ret[3] = strdup(ret[1]);
732 // Before we didn't check for the return type of strdup, here we will
734 bool any_null = false;
735 for (int i = 0; i < 4; ++i)
736 any_null = ret[i] == nil || any_null;
738 if (any_null)
739 for (int i = 0; i < 4; ++i)
740 if (ret[i] != nil)
741 free(ret[i]);
743 if (i == 0 || any_null) {
744 free(s);
745 free(ret);
746 return nil;
749 return ret;
752 // Given an event, try to understand what the user wants. If the
753 // return value is ADD_CHAR then `input' is a pointer to a string that
754 // will need to be free'ed.
755 enum action parse_event(Display *d, XKeyPressedEvent *ev, XIC xic, char **input) {
756 if (ev->keycode == XKeysymToKeycode(d, XK_BackSpace))
757 return DEL_CHAR;
759 if (ev->keycode == XKeysymToKeycode(d, XK_Tab))
760 return ev->state & ShiftMask ? PREV_COMPL : NEXT_COMPL;
762 if (ev->keycode == XKeysymToKeycode(d, XK_Return))
763 return CONFIRM;
765 if (ev->keycode == XKeysymToKeycode(d, XK_Escape))
766 return EXIT;
768 // try to read what the user pressed
769 char str[SYM_BUF_SIZE] = {0};
770 Status s = 0;
771 Xutf8LookupString(xic, ev, str, SYM_BUF_SIZE, 0, &s);
772 if (s == XBufferOverflow) {
773 // should not happen since there are no utf-8 characters larger
774 // than 24bits
775 fprintf(stderr, "Buffer overflow when trying to create keyboard symbol map.\n");
776 return EXIT;
779 if (ev->state & ControlMask) {
780 if (!strcmp(str, "")) // C-u
781 return DEL_LINE;
782 if (!strcmp(str, "")) // C-w
783 return DEL_WORD;
784 if (!strcmp(str, "")) // C-h
785 return DEL_CHAR;
786 if (!strcmp(str, "\r")) // C-m
787 return CONFIRM;
788 if (!strcmp(str, "")) // C-p
789 return PREV_COMPL;
790 if (!strcmp(str, "")) // C-n
791 return NEXT_COMPL;
792 if (!strcmp(str, "")) // C-c
793 return EXIT;
794 if (!strcmp(str, "\t")) // C-i
795 return TOGGLE_FIRST_SELECTED;
798 *input = strdup(str);
799 if (*input == nil) {
800 fprintf(stderr, "Error while allocating memory for key.\n");
801 return EXIT;
804 return ADD_CHAR;
807 // Given the name of the program (argv[0]?) print a small help on stderr
808 void usage(char *prgname) {
809 fprintf(stderr, "%s [-hva] [-p prompt] [-x coord] [-y coord] [-W width] [-H height]\n"
810 " [-P padding] [-l layout] [-f font] [-b borders] [-B colors]\n"
811 " [-t color] [-T color] [-c color] [-C color] [-s color] [-S color]\n"
812 " [-w window_id]\n", prgname);
815 int main(int argc, char **argv) {
816 #ifdef HAVE_PLEDGE
817 // stdio & rpat: to read and write stdio/stdout
818 // unix: to connect to Xorg
819 pledge("stdio rpath unix", "");
820 #endif
822 char *sep = nil;
824 // by default the first completion isn't selected
825 bool first_selected = false;
827 // our parent window
828 char *parent_window_id = nil;
830 // the user can input arbitrary text
831 bool free_text = true;
833 // first round of args parsing
834 int ch;
835 while ((ch = getopt(argc, argv, ARGS)) != -1) {
836 switch (ch) {
837 case 'h': // help
838 usage(*argv);
839 return 0;
840 case 'v': // version
841 fprintf(stderr, "%s version: %s\n", *argv, VERSION);
842 return 0;
843 case 'e': // embed
844 parent_window_id = strdup(optarg);
845 check_allocation(parent_window_id);
846 break;
847 case 'd': {
848 sep = strdup(optarg);
849 check_allocation(sep);
851 case 'A': {
852 free_text = false;
853 break;
855 default:
856 break;
860 // read the lines from stdin
861 char **lines = calloc(INITIAL_ITEMS, sizeof(char*));
862 check_allocation(lines);
863 size_t nlines = readlines(&lines, INITIAL_ITEMS);
864 char **vlines = nil;
865 if (sep != nil) {
866 int l = strlen(sep);
867 vlines = calloc(nlines, sizeof(char*));
868 check_allocation(vlines);
870 for (int i = 0; lines[i] != nil; i++) {
871 char *t = strstr(lines[i], sep);
872 if (t == nil)
873 vlines[i] = lines[i];
874 else
875 vlines[i] = t + l;
879 setlocale(LC_ALL, getenv("LANG"));
881 enum state status = LOOPING;
883 // where the monitor start (used only with xinerama)
884 int offset_x = 0;
885 int offset_y = 0;
887 // width and height of the window
888 int width = 400;
889 int height = 20;
891 // position on the screen
892 int x = 0;
893 int y = 0;
895 // the default padding
896 int padding = 10;
898 // the default borders
899 int border_n = 0;
900 int border_e = 0;
901 int border_s = 0;
902 int border_w = 0;
904 // the prompt. We duplicate the string so later is easy to free (in
905 // the case the user provide its own prompt)
906 char *ps1 = strdup("$ ");
907 check_allocation(ps1);
909 // same for the font name
910 char *fontname = strdup(default_fontname);
911 check_allocation(fontname);
913 int textlen = 10;
914 char *text = malloc(textlen * sizeof(char));
915 check_allocation(text);
917 /* struct completions *cs = filter(text, lines); */
918 struct completions *cs = compls_new(nlines);
919 check_allocation(cs);
921 // start talking to xorg
922 Display *d = XOpenDisplay(nil);
923 if (d == nil) {
924 fprintf(stderr, "Could not open display!\n");
925 return EX_UNAVAILABLE;
928 Window parent_window;
929 bool embed = true;
930 if (! (parent_window_id && (parent_window = strtol(parent_window_id, nil, 0)))) {
931 parent_window = DefaultRootWindow(d);
932 embed = false;
935 // get display size
936 int d_width;
937 int d_height;
938 get_wh(d, &parent_window, &d_width, &d_height);
940 #ifdef USE_XINERAMA
941 if (!embed && XineramaIsActive(d)) {
942 // find the mice
943 int number_of_screens = XScreenCount(d);
944 Window r;
945 Window root;
946 int root_x, root_y, win_x, win_y;
947 unsigned int mask;
948 bool res;
949 for (int i = 0; i < number_of_screens; ++i) {
950 root = XRootWindow(d, i);
951 res = XQueryPointer(d, root, &r, &r, &root_x, &root_y, &win_x, &win_y, &mask);
952 if (res) break;
954 if (!res) {
955 fprintf(stderr, "No mouse found.\n");
956 root_x = 0;
957 root_y = 0;
960 // now find in which monitor the mice is on
961 int monitors;
962 XineramaScreenInfo *info = XineramaQueryScreens(d, &monitors);
963 if (info) {
964 for (int i = 0; i < monitors; ++i) {
965 if (info[i].x_org <= root_x && root_x <= (info[i].x_org + info[i].width)
966 && info[i].y_org <= root_y && root_y <= (info[i].y_org + info[i].height)) {
967 offset_x = info[i].x_org;
968 offset_y = info[i].y_org;
969 d_width = info[i].width;
970 d_height = info[i].height;
971 break;
975 XFree(info);
977 #endif
979 Colormap cmap = DefaultColormap(d, DefaultScreen(d));
980 XColor p_fg, p_bg,
981 compl_fg, compl_bg,
982 compl_highlighted_fg, compl_highlighted_bg,
983 border_n_bg, border_e_bg, border_s_bg, border_w_bg;
985 bool horizontal_layout = true;
987 // read resource
988 XrmInitialize();
989 char *xrm = XResourceManagerString(d);
990 XrmDatabase xdb = nil;
991 if (xrm != nil) {
992 xdb = XrmGetStringDatabase(xrm);
993 XrmValue value;
994 char *datatype[20];
996 if (XrmGetResource(xdb, "MyMenu.font", "*", datatype, &value) == true) {
997 fontname = strdup(value.addr);
998 check_allocation(fontname);
999 } else {
1000 fprintf(stderr, "no font defined, using %s\n", fontname);
1003 if (XrmGetResource(xdb, "MyMenu.layout", "*", datatype, &value) == true)
1004 horizontal_layout = !strcmp(value.addr, "horizontal");
1005 else
1006 fprintf(stderr, "no layout defined, using horizontal\n");
1008 if (XrmGetResource(xdb, "MyMenu.prompt", "*", datatype, &value) == true) {
1009 free(ps1);
1010 ps1 = normalize_str(value.addr);
1011 } else {
1012 fprintf(stderr, "no prompt defined, using \"%s\" as default\n", ps1);
1015 if (XrmGetResource(xdb, "MyMenu.width", "*", datatype, &value) == true)
1016 width = parse_int_with_percentage(value.addr, width, d_width);
1017 else
1018 fprintf(stderr, "no width defined, using %d\n", width);
1020 if (XrmGetResource(xdb, "MyMenu.height", "*", datatype, &value) == true)
1021 height = parse_int_with_percentage(value.addr, height, d_height);
1022 else
1023 fprintf(stderr, "no height defined, using %d\n", height);
1025 if (XrmGetResource(xdb, "MyMenu.x", "*", datatype, &value) == true)
1026 x = parse_int_with_pos(value.addr, x, d_width, width);
1027 else
1028 fprintf(stderr, "no x defined, using %d\n", x);
1030 if (XrmGetResource(xdb, "MyMenu.y", "*", datatype, &value) == true)
1031 y = parse_int_with_pos(value.addr, y, d_height, height);
1032 else
1033 fprintf(stderr, "no y defined, using %d\n", y);
1035 if (XrmGetResource(xdb, "MyMenu.padding", "*", datatype, &value) == true)
1036 padding = parse_integer(value.addr, padding);
1037 else
1038 fprintf(stderr, "no padding defined, using %d\n", padding);
1040 if (XrmGetResource(xdb, "MyMenu.border.size", "*", datatype, &value) == true) {
1041 char **borders = parse_csslike(value.addr);
1042 if (borders != nil) {
1043 border_n = parse_integer(borders[0], 0);
1044 border_e = parse_integer(borders[1], 0);
1045 border_s = parse_integer(borders[2], 0);
1046 border_w = parse_integer(borders[3], 0);
1047 } else {
1048 fprintf(stderr, "error while parsing MyMenu.border.size\n");
1050 } else {
1051 fprintf(stderr, "no border defined, using 0.\n");
1054 XColor tmp;
1055 // TODO: tmp needs to be free'd after every allocation?
1057 // prompt
1058 if (XrmGetResource(xdb, "MyMenu.prompt.foreground", "*", datatype, &value) == true)
1059 XAllocNamedColor(d, cmap, value.addr, &p_fg, &tmp);
1060 else
1061 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
1063 if (XrmGetResource(xdb, "MyMenu.prompt.background", "*", datatype, &value) == true)
1064 XAllocNamedColor(d, cmap, value.addr, &p_bg, &tmp);
1065 else
1066 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
1068 // completion
1069 if (XrmGetResource(xdb, "MyMenu.completion.foreground", "*", datatype, &value) == true)
1070 XAllocNamedColor(d, cmap, value.addr, &compl_fg, &tmp);
1071 else
1072 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
1074 if (XrmGetResource(xdb, "MyMenu.completion.background", "*", datatype, &value) == true)
1075 XAllocNamedColor(d, cmap, value.addr, &compl_bg, &tmp);
1076 else
1077 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
1079 // completion highlighted
1080 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.foreground", "*", datatype, &value) == true)
1081 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_fg, &tmp);
1082 else
1083 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
1085 if (XrmGetResource(xdb, "MyMenu.completion_highlighted.background", "*", datatype, &value) == true)
1086 XAllocNamedColor(d, cmap, value.addr, &compl_highlighted_bg, &tmp);
1087 else
1088 XAllocNamedColor(d, cmap, "white", &compl_highlighted_bg, &tmp);
1090 // border
1091 if (XrmGetResource(xdb, "MyMenu.border.color", "*", datatype, &value) == true) {
1092 char **colors = parse_csslike(value.addr);
1093 if (colors != nil) {
1094 XAllocNamedColor(d, cmap, colors[0], &border_n_bg, &tmp);
1095 XAllocNamedColor(d, cmap, colors[1], &border_e_bg, &tmp);
1096 XAllocNamedColor(d, cmap, colors[2], &border_s_bg, &tmp);
1097 XAllocNamedColor(d, cmap, colors[3], &border_w_bg, &tmp);
1098 } else {
1099 fprintf(stderr, "error while parsing MyMenu.border.color\n");
1101 } else {
1102 XAllocNamedColor(d, cmap, "white", &border_n_bg, &tmp);
1103 XAllocNamedColor(d, cmap, "white", &border_e_bg, &tmp);
1104 XAllocNamedColor(d, cmap, "white", &border_s_bg, &tmp);
1105 XAllocNamedColor(d, cmap, "white", &border_w_bg, &tmp);
1107 } else {
1108 XColor tmp;
1109 XAllocNamedColor(d, cmap, "white", &p_fg, &tmp);
1110 XAllocNamedColor(d, cmap, "black", &p_bg, &tmp);
1111 XAllocNamedColor(d, cmap, "white", &compl_fg, &tmp);
1112 XAllocNamedColor(d, cmap, "black", &compl_bg, &tmp);
1113 XAllocNamedColor(d, cmap, "black", &compl_highlighted_fg, &tmp);
1114 XAllocNamedColor(d, cmap, "white", &border_n_bg, &tmp);
1115 XAllocNamedColor(d, cmap, "white", &border_e_bg, &tmp);
1116 XAllocNamedColor(d, cmap, "white", &border_s_bg, &tmp);
1117 XAllocNamedColor(d, cmap, "white", &border_w_bg, &tmp);
1120 // second round of args parsing
1121 optind = 0; // reset the option index
1122 while ((ch = getopt(argc, argv, ARGS)) != -1) {
1123 switch (ch) {
1124 case 'a':
1125 first_selected = true;
1126 break;
1127 case 'A':
1128 // free_text -- this case was already catched
1129 break;
1130 case 'd':
1131 // separator -- this case was already catched
1132 break;
1133 case 'e':
1134 // (embedding mymenu) this case was already catched.
1135 break;
1136 case 'p': {
1137 char *newprompt = strdup(optarg);
1138 if (newprompt != nil) {
1139 free(ps1);
1140 ps1 = newprompt;
1142 break;
1144 case 'x':
1145 x = parse_int_with_pos(optarg, x, d_width, width);
1146 break;
1147 case 'y':
1148 y = parse_int_with_pos(optarg, y, d_height, height);
1149 break;
1150 case 'P':
1151 padding = parse_integer(optarg, padding);
1152 break;
1153 case 'l':
1154 horizontal_layout = !strcmp(optarg, "horizontal");
1155 break;
1156 case 'f': {
1157 char *newfont = strdup(optarg);
1158 if (newfont != nil) {
1159 free(fontname);
1160 fontname = newfont;
1162 break;
1164 case 'W':
1165 width = parse_int_with_percentage(optarg, width, d_width);
1166 break;
1167 case 'H':
1168 height = parse_int_with_percentage(optarg, height, d_height);
1169 break;
1170 case 'b': {
1171 char **borders = parse_csslike(optarg);
1172 if (borders != nil) {
1173 border_n = parse_integer(borders[0], 0);
1174 border_e = parse_integer(borders[1], 0);
1175 border_s = parse_integer(borders[2], 0);
1176 border_w = parse_integer(borders[3], 0);
1177 } else {
1178 fprintf(stderr, "Error parsing b option\n");
1180 break;
1182 case 'B': {
1183 char **colors = parse_csslike(optarg);
1184 if (colors != nil) {
1185 XColor tmp;
1186 XAllocNamedColor(d, cmap, colors[0], &border_n_bg, &tmp);
1187 XAllocNamedColor(d, cmap, colors[1], &border_e_bg, &tmp);
1188 XAllocNamedColor(d, cmap, colors[2], &border_s_bg, &tmp);
1189 XAllocNamedColor(d, cmap, colors[3], &border_w_bg, &tmp);
1190 } else {
1191 fprintf(stderr, "error while parsing B option\n");
1193 break;
1195 case 't': {
1196 XColor tmp;
1197 XAllocNamedColor(d, cmap, optarg, &p_fg, &tmp);
1198 break;
1200 case 'T': {
1201 XColor tmp;
1202 XAllocNamedColor(d, cmap, optarg, &p_bg, &tmp);
1203 break;
1205 case 'c': {
1206 XColor tmp;
1207 XAllocNamedColor(d, cmap, optarg, &compl_fg, &tmp);
1208 break;
1210 case 'C': {
1211 XColor tmp;
1212 XAllocNamedColor(d, cmap, optarg, &compl_bg, &tmp);
1213 break;
1215 case 's': {
1216 XColor tmp;
1217 XAllocNamedColor(d, cmap, optarg, &compl_highlighted_fg, &tmp);
1218 break;
1220 case 'S': {
1221 XColor tmp;
1222 XAllocNamedColor(d, cmap, optarg, &compl_highlighted_bg, &tmp);
1223 break;
1225 default:
1226 fprintf(stderr, "Unrecognized option %c\n", ch);
1227 status = ERR;
1228 break;
1232 // since only now we know if the first should be selected, update
1233 // the completion here
1234 update_completions(cs, text, lines, vlines, first_selected);
1236 // load the font
1237 #ifdef USE_XFT
1238 XftFont *font = XftFontOpenName(d, DefaultScreen(d), fontname);
1239 #else
1240 char **missing_charset_list;
1241 int missing_charset_count;
1242 XFontSet font = XCreateFontSet(d, fontname, &missing_charset_list, &missing_charset_count, nil);
1243 if (font == nil) {
1244 fprintf(stderr, "Unable to load the font(s) %s\n", fontname);
1245 return EX_UNAVAILABLE;
1247 #endif
1249 // create the window
1250 XSetWindowAttributes attr;
1251 attr.override_redirect = true;
1252 attr.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
1254 Window w = XCreateWindow(d, // display
1255 parent_window, // parent
1256 x + offset_x, y + offset_y, // x y
1257 width, height, // w h
1258 0, // border width
1259 CopyFromParent, // depth
1260 InputOutput, // class
1261 CopyFromParent, // visual
1262 CWEventMask | CWOverrideRedirect, // value mask (CWBackPixel in the future also?)
1263 &attr);
1265 set_win_atoms_hints(d, w, width, height);
1267 // we want some events
1268 XSelectInput(d, w, StructureNotifyMask | KeyPressMask | KeymapStateMask | ButtonPressMask);
1269 XMapRaised(d, w);
1271 // if embed, listen for other events as well
1272 if (embed) {
1273 XSelectInput(d, parent_window, FocusChangeMask);
1274 Window *children, parent, root;
1275 unsigned int children_no;
1276 if (XQueryTree(d, parent_window, &root, &parent, &children, &children_no) && children) {
1277 for (unsigned int i = 0; i < children_no && children[i] != w; ++i)
1278 XSelectInput(d, children[i], FocusChangeMask);
1279 XFree(children);
1281 grabfocus(d, w);
1284 // grab keyboard
1285 take_keyboard(d, w);
1287 // Create some graphics contexts
1288 XGCValues values;
1289 /* values.font = font->fid; */
1291 struct rendering r = {
1292 .d = d,
1293 .w = w,
1294 .width = width,
1295 .height = height,
1296 .padding = padding,
1297 .x_zero = border_w,
1298 .y_zero = border_n,
1299 .offset = 0,
1300 .border_n = border_n,
1301 .border_e = border_e,
1302 .border_s = border_s,
1303 .border_w = border_w,
1304 .horizontal_layout = horizontal_layout,
1305 .ps1 = ps1,
1306 .ps1len = strlen(ps1),
1307 .prompt = XCreateGC(d, w, 0, &values),
1308 .prompt_bg = XCreateGC(d, w, 0, &values),
1309 .completion = XCreateGC(d, w, 0, &values),
1310 .completion_bg = XCreateGC(d, w, 0, &values),
1311 .completion_highlighted = XCreateGC(d, w, 0, &values),
1312 .completion_highlighted_bg = XCreateGC(d, w, 0, &values),
1313 .border_n_bg = XCreateGC(d, w, 0, &values),
1314 .border_e_bg = XCreateGC(d, w, 0, &values),
1315 .border_s_bg = XCreateGC(d, w, 0, &values),
1316 .border_w_bg = XCreateGC(d, w, 0, &values),
1317 #ifdef USE_XFT
1318 .font = font,
1319 #else
1320 .font = &font,
1321 #endif
1324 #ifdef USE_XFT
1325 r.xftdraw = XftDrawCreate(d, w, DefaultVisual(d, 0), DefaultColormap(d, 0));
1327 // prompt
1328 XRenderColor xrcolor;
1329 xrcolor.red = p_fg.red;
1330 xrcolor.green = p_fg.red;
1331 xrcolor.blue = p_fg.red;
1332 xrcolor.alpha = 65535;
1333 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_prompt);
1335 // completion
1336 xrcolor.red = compl_fg.red;
1337 xrcolor.green = compl_fg.green;
1338 xrcolor.blue = compl_fg.blue;
1339 xrcolor.alpha = 65535;
1340 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion);
1342 // completion highlighted
1343 xrcolor.red = compl_highlighted_fg.red;
1344 xrcolor.green = compl_highlighted_fg.green;
1345 xrcolor.blue = compl_highlighted_fg.blue;
1346 xrcolor.alpha = 65535;
1347 XftColorAllocValue(d, DefaultVisual(d, 0), DefaultColormap(d, 0), &xrcolor, &r.xft_completion_highlighted);
1348 #endif
1350 // load the colors in our GCs
1351 XSetForeground(d, r.prompt, p_fg.pixel);
1352 XSetForeground(d, r.prompt_bg, p_bg.pixel);
1353 XSetForeground(d, r.completion, compl_fg.pixel);
1354 XSetForeground(d, r.completion_bg, compl_bg.pixel);
1355 XSetForeground(d, r.completion_highlighted, compl_highlighted_fg.pixel);
1356 XSetForeground(d, r.completion_highlighted_bg, compl_highlighted_bg.pixel);
1357 XSetForeground(d, r.border_n_bg, border_n_bg.pixel);
1358 XSetForeground(d, r.border_e_bg, border_e_bg.pixel);
1359 XSetForeground(d, r.border_s_bg, border_s_bg.pixel);
1360 XSetForeground(d, r.border_w_bg, border_w_bg.pixel);
1362 // open the X input method
1363 XIM xim = XOpenIM(d, xdb, resname, resclass);
1364 check_allocation(xim);
1366 XIMStyles *xis = nil;
1367 if (XGetIMValues(xim, XNQueryInputStyle, &xis, NULL) || !xis) {
1368 fprintf(stderr, "Input Styles could not be retrieved\n");
1369 return EX_UNAVAILABLE;
1372 XIMStyle bestMatchStyle = 0;
1373 for (int i = 0; i < xis->count_styles; ++i) {
1374 XIMStyle ts = xis->supported_styles[i];
1375 if (ts == (XIMPreeditNothing | XIMStatusNothing)) {
1376 bestMatchStyle = ts;
1377 break;
1380 XFree(xis);
1382 if (!bestMatchStyle) {
1383 fprintf(stderr, "No matching input style could be determined\n");
1386 XIC xic = XCreateIC(xim, XNInputStyle, bestMatchStyle, XNClientWindow, w, XNFocusWindow, w, NULL);
1387 check_allocation(xic);
1389 // draw the window for the first time
1390 draw(&r, text, cs);
1392 // main loop
1393 while (status == LOOPING) {
1394 XEvent e;
1395 XNextEvent(d, &e);
1397 if (XFilterEvent(&e, w))
1398 continue;
1400 switch (e.type) {
1401 case KeymapNotify:
1402 XRefreshKeyboardMapping(&e.xmapping);
1403 break;
1405 case FocusIn:
1406 // re-grab focus
1407 if (e.xfocus.window != w)
1408 grabfocus(d, w);
1409 break;
1411 case VisibilityNotify:
1412 if (e.xvisibility.state != VisibilityUnobscured)
1413 XRaiseWindow(d, w);
1414 break;
1416 case MapNotify:
1417 /* fprintf(stderr, "Map Notify!\n"); */
1418 /* TODO: update the computed window and height! */
1419 /* get_wh(d, &w, width, height); */
1420 draw(&r, text, cs);
1421 break;
1423 case KeyPress: {
1424 XKeyPressedEvent *ev = (XKeyPressedEvent*)&e;
1426 char *input;
1427 switch (parse_event(d, ev, xic, &input)) {
1428 case EXIT:
1429 status = ERR;
1430 break;
1432 case CONFIRM: {
1433 status = OK;
1434 if ((cs->selected != -1) || (cs->lenght > 0 && first_selected)) {
1435 // if there is something selected expand it and return
1436 int index = cs->selected == -1 ? 0 : cs->selected;
1437 struct completion *c = cs->completions;
1438 while (true) {
1439 if (index == 0)
1440 break;
1441 c++;
1442 index--;
1444 char *t = c->rcompletion;
1445 free(text);
1446 text = strdup(t);
1447 if (text == nil) {
1448 fprintf(stderr, "Memory allocation error\n");
1449 status = ERR;
1451 textlen = strlen(text);
1452 } else {
1453 if (!free_text) {
1454 // cannot accept arbitrary text
1455 status = LOOPING;
1458 break;
1461 case PREV_COMPL: {
1462 complete(cs, first_selected, true, &text, &textlen, &status);
1463 r.offset = cs->selected;
1464 break;
1467 case NEXT_COMPL: {
1468 complete(cs, first_selected, false, &text, &textlen, &status);
1469 r.offset = cs->selected;
1470 break;
1473 case DEL_CHAR:
1474 popc(text);
1475 update_completions(cs, text, lines, vlines, first_selected);
1476 r.offset = 0;
1477 break;
1479 case DEL_WORD: {
1480 popw(text);
1481 update_completions(cs, text, lines, vlines, first_selected);
1482 break;
1485 case DEL_LINE: {
1486 for (int i = 0; i < textlen; ++i)
1487 text[i] = 0;
1488 update_completions(cs, text, lines, vlines, first_selected);
1489 r.offset = 0;
1490 break;
1493 case ADD_CHAR: {
1494 int str_len = strlen(input);
1496 // sometimes a strange key is pressed (i.e. ctrl alone),
1497 // so input will be empty. Don't need to update completion
1498 // in this case
1499 if (str_len == 0)
1500 break;
1502 for (int i = 0; i < str_len; ++i) {
1503 textlen = pushc(&text, textlen, input[i]);
1504 if (textlen == -1) {
1505 fprintf(stderr, "Memory allocation error\n");
1506 status = ERR;
1507 break;
1510 if (status != ERR) {
1511 update_completions(cs, text, lines, vlines, first_selected);
1512 free(input);
1514 r.offset = 0;
1515 break;
1518 case TOGGLE_FIRST_SELECTED:
1519 first_selected = !first_selected;
1520 if (first_selected && cs->selected < 0)
1521 cs->selected = 0;
1522 if (!first_selected && cs->selected == 0)
1523 cs->selected = -1;
1524 break;
1528 case ButtonPress: {
1529 XButtonPressedEvent *ev = (XButtonPressedEvent*)&e;
1530 /* if (ev->button == Button1) { /\* click *\/ */
1531 /* int x = ev->x - r.border_w; */
1532 /* int y = ev->y - r.border_n; */
1533 /* fprintf(stderr, "Click @ (%d, %d)\n", x, y); */
1534 /* } */
1536 if (ev->button == Button4) /* scroll up */
1537 r.offset = MAX((ssize_t)r.offset - 1, 0);
1539 if (ev->button == Button5) /* scroll down */
1540 r.offset = MIN(r.offset + 1, cs->lenght - 1);
1542 break;
1546 draw(&r, text, cs);
1549 if (status == OK)
1550 printf("%s\n", text);
1552 release_keyboard(r.d);
1554 #ifdef USE_XFT
1555 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_prompt);
1556 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion);
1557 XftColorFree(r.d, DefaultVisual(r.d, 0), DefaultColormap(r.d, 0), &r.xft_completion_highlighted);
1558 #endif
1560 free(ps1);
1561 free(fontname);
1562 free(text);
1564 char *l = nil;
1565 char **lns = lines;
1566 while ((l = *lns) != nil) {
1567 free(l);
1568 ++lns;
1571 free(lines);
1572 free(vlines);
1573 compls_delete(cs);
1575 XDestroyWindow(r.d, r.w);
1576 XCloseDisplay(r.d);
1578 return status != OK;